package com.ssj.push.util.jiguang;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
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.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author yangcan 类描述:极光推送工具类
 */
public class MessagePushUtils {
    protected static final Logger logger = LoggerFactory.getLogger("aijia");
    static {
        //小塾学伴ios家长端
        String	PARENT_IOS_APP_KEY       = "72974d72072939cf16871282";
        String  PARENT_IOS_MASTER_SECRET = "2aab2aa2e783b922ca6fe319";

        //小塾学伴android家长端
        String	PARENT_ANDROID_APP_KEY       = "72974d72072939cf16871282";
        String  PARENT_ANDROID_MASTER_SECRET = "2aab2aa2e783b922ca6fe319";

        //小塾学伴ios老师端
        String	TEACHER_IOS_APP_KEY       = "e9dc033252bafb46d6fdc7a1";
        String  TEACHER_IOS_MASTER_SECRET = "da11994ea0ef15c7b509ead1";

        //小塾学伴android老师端
        String	TEACHER_ANDROID_APP_KEY       = "e9dc033252bafb46d6fdc7a1";
        String  TEACHER_ANDROID_MASTER_SECRET = "da11994ea0ef15c7b509ead1";

        //小塾学伴ios学生手机端
        String	STUDENT_IOS_APP_KEY       = "2ffc2aa60e13f609df94821e";
        String  STUDENT_IOS_MASTER_SECRET = "3ee60b95306f6dcbc42b1626";

        //小塾学伴android学生手机端
        String	STUDENT_ANDROID_APP_KEY       = "2ffc2aa60e13f609df94821e";
        String  STUDENT_ANDROID_MASTER_SECRET = "3ee60b95306f6dcbc42b1626";

        //小塾学伴ios学生pad端
        String	STUDENT_IOS_PAD_APP_KEY       = "5aa3c45483cda0876903c0e5";
        String  STUDENT_IOS_PAD_MASTER_SECRET = "c7d3f169b7331e2ba4c8940b";

        //小塾学伴android学生pad端
        String	STUDENT_ANDROID_PAD_APP_KEY       = "5aa3c45483cda0876903c0e5";
        String  STUDENT_ANDROID_PAD_MASTER_SECRET = "c7d3f169b7331e2ba4c8940b";


        parentAndoridClient = new JPushClient(PARENT_ANDROID_MASTER_SECRET,PARENT_ANDROID_APP_KEY, null, ClientConfig.getInstance());
        parentIosClient = new JPushClient(PARENT_IOS_MASTER_SECRET,PARENT_IOS_APP_KEY, null, ClientConfig.getInstance());

        teacherAndroidClient = new JPushClient(TEACHER_ANDROID_MASTER_SECRET,TEACHER_ANDROID_APP_KEY, null, ClientConfig.getInstance());
        teacherIosClient = new JPushClient(TEACHER_IOS_MASTER_SECRET,TEACHER_IOS_APP_KEY, null, ClientConfig.getInstance());

        studentAndroidClient = new JPushClient(STUDENT_ANDROID_MASTER_SECRET,STUDENT_ANDROID_APP_KEY, null, ClientConfig.getInstance());
        studentIosClient = new JPushClient(STUDENT_IOS_MASTER_SECRET,STUDENT_IOS_APP_KEY, null, ClientConfig.getInstance());

        conchPadAndroidClient = new JPushClient(STUDENT_ANDROID_PAD_MASTER_SECRET,STUDENT_ANDROID_PAD_APP_KEY, null, ClientConfig.getInstance());
        conchPadIosClient = new JPushClient(STUDENT_IOS_PAD_MASTER_SECRET,STUDENT_IOS_PAD_APP_KEY, null, ClientConfig.getInstance());
    }
    public static JPushClient parentAndoridClient; //家长端android
    public static JPushClient parentIosClient; //家长端ios

    private static JPushClient teacherAndroidClient; //老师端android
    private static JPushClient teacherIosClient; //老师端ios

    public static JPushClient studentIosClient; //小塾学生端ios
    public static JPushClient studentAndroidClient; //小塾学生端android

    public static JPushClient conchPadIosClient; //小塾学伴ios pad版
    public static JPushClient conchPadAndroidClient; //小塾学伴android pad版

    private static Integer sysEnv = Integer.parseInt(Optional.ofNullable(SystemResourceLocator.getValue("SYS_ENV")).orElse("0").toString());
    //private static Integer sysEnv = 0;

    private static JPushClient	getJPushClient(String platform,int platformType) {
        JPushClient jPushClient = null;
        if(PushConstants.PUSH_ANDROID.equals(platform)) {
            //1:小塾硬件端 2:家长端 3:小塾学生端 4:老师端 5:校长端 6:小塾pad端
            switch (platformType) {
                case 1:
                    jPushClient = conchPadAndroidClient;
                    break;
                case 2:
                    jPushClient = parentAndoridClient;
                    break;
                case 3:
                    jPushClient = studentAndroidClient;
                    break;
                case 4:
                    jPushClient = teacherAndroidClient;
                    break;
                case 5:
                    break;
                case 6:
                    jPushClient = conchPadAndroidClient;
                    break;
            }
        }else if(PushConstants.PUSH_IOS.equals(platform)){
            //2:家长端 3:小塾学生端 4:老师端 5:校长端 6:小塾pad端
            switch (platformType) {
                case 2:
                    jPushClient = parentIosClient;
                    break;
                case 3:
                    jPushClient = studentIosClient;
                    break;
                case 4:
                    jPushClient = teacherIosClient;
                    break;
                case 5:
                    break;
                case 6:
                    jPushClient = conchPadIosClient;
                    break;
            }
        }
        return jPushClient;
    }


    /**
     * @param token
     * @param title
     * @param content
     * @param platformType 1:小塾硬件端 2:家长端 3:小塾学生端 4:老师端 5:校长端 6:小塾pad端
     * @param messageType notify:通知栏消息 ,message:应用内/透传消息/静默消息
     * @param custom 自定义内容
     * @return

     * 方法说明:推送单个安卓设备

     * 创立日期:2018年8月23日 上午11:02:34
     * 创建人:yangcan

     */
    public static PushResult pushByAndroid(String token, String title, String content, int platformType, String messageType, Map<String, Object> custom) {
        logger.error("android平台{},推送别名{},推送内容{}",platformType,token,content);
        try{
            //推送入参
            JPushClient jPushClient = getJPushClient(PushConstants.PUSH_ANDROID, platformType);
            if(jPushClient != null) {
                PushPayload payload = getPushPayloadByPushSingleAndroid(token, title, content, messageType, custom);
                return jPushClient.sendPush(payload);
            }
        }catch (Exception e){
            logger.error("平台{},极光推送单个安卓设备异常:{}",platformType,e);
        }
        return null;
    }

    /**
     * @param title
     * @param content
     * @param platformType
     * @param messageType notify:通知栏消息 ,message:应用内/透传消息/静默消息
     * @return

     * 方法说明:推送所有安卓设备 1:小塾硬件端 2:家长端 3:小塾学生端 4:老师端 5:校长端 6:小塾pad端

     * 创立日期:2018年8月23日 下午1:57:16
     * 创建人:yangcan

     */
    public static PushResult pushAllByAndroid(String title,String content,int platformType,String messageType) {
        logger.error("平台{},推送内容{}",platformType,content);
        try{
            //推送入参
            JPushClient jPushClient = getJPushClient(PushConstants.PUSH_ANDROID, platformType);
            if(jPushClient != null) {
                if("message".equals(messageType)) {
                    //推送目标,单设备推送
                    PushPayload payload = getPushPayloadByPushAllAndroid(content);
                    return jPushClient.sendPush(payload);
                }
            }
        }catch (Exception e){
            logger.error("极光推送所有安卓设备异常:",e);
        }
        return null;
    }

    /**
     * @param token
     * @param content
     * @param platformType 2:家长端 3:小塾学生端 4:老师端 5:校长端 6:小塾pad端
     * @return

     * 方法说明:推送单个ios设备

     * 创立日期:2018年8月23日 上午11:02:51
     * 创建人:yangcan

     */
    public static PushResult pushByIos(String token,String content,int platformType,String sound,Map<String,Object> custom,int iosEnv,int bagde) {
        logger.error("ios平台{},推送别名{},推送内容{}",platformType,token,content);
        try{
            //推送入参
            JPushClient jPushClient = getJPushClient(PushConstants.PUSH_IOS, platformType);
            if(jPushClient != null) {
                PushPayload payload = getPushPayloadByPushSingleIos(token, content, sound, custom, bagde);
                return jPushClient.sendPush(payload);
            }
        }catch (Exception e){
            logger.error("平台{},极光推送单个ios设备异常:{}",platformType,e);
        }
        return null;
    }


    /**
     * @param content
     * @param platformType
     * @return

     * 方法说明:推送所有ios设备 应用内消息

     * 创立日期:2018年8月23日 下午2:01:41
     * 创建人:yangcan

     */
    public static PushResult pushAllByIosAPNS(String content, int platformType, String sound, Map<String,Object> custom, int iosEnv) {
        try{
            //推送入参
            JPushClient jPushClient = getJPushClient(PushConstants.PUSH_IOS, platformType);
            if(jPushClient != null) {
                //推送目标,单设备推送
                PushPayload payload = getPushPayloadByPushAllIos(JSON.toJSONString(custom));
                return jPushClient.sendPush(payload);
            }
        }catch (Exception e){
            logger.error("极光推送所有ios设备异常:",e);
        }
        return null;
    }

    public static PushPayload getPushPayloadByPushSingleAndroid(String token, String title, String content, String messageType, Map<String, Object> custom) {
        PushPayload payload;
        //判断是开发环境还是生产环境
        if(sysEnv == 1) {
            //生产环境
            if("message".equals(messageType)) {
                //推送应用内消息
                payload = PushPayload.newBuilder()
                        .setPlatform(Platform.android())
                        .setAudience(Audience.registrationId(token))
                        .setMessage(Message.content(content))
                        .setOptions(Options.newBuilder().setApnsProduction(true).build())
                        .build();
            }else {
                //推送通知消息
                payload = PushPayload.newBuilder()
                        .setPlatform(Platform.android())
                        .setAudience(Audience.registrationId(token))
                        .setNotification(Notification.android(content,title,null))
                        .setOptions(Options.newBuilder().setApnsProduction(true).build())
                        .build();
            }
        }else {
            if("message".equals(messageType)) {
                payload = PushPayload.newBuilder()
                        .setPlatform(Platform.android())
                        .setAudience(Audience.registrationId(token))
                        .setMessage(Message.content(content))
                        .build();
            }else {
                //推送通知消息
                payload = PushPayload.newBuilder()
                        .setPlatform(Platform.android())
                        .setAudience(Audience.registrationId(token))
                        .setNotification(Notification.android(content,title,null))
                        .build();
            }
        }
        return payload;
    }

    public static PushPayload getPushPayloadByPushSingleIos(String token,String content,String sound,Map<String,Object> custom,int bagde) {
        //推送应用内消息
        Map<String, String> extra = JSON.parseObject(JSON.toJSONString(custom),new TypeReference<Map<String,String>>(){});
        PushPayload payload;
        //判断是开发环境还是生产环境
        if(sysEnv == 1) {
            //生产环境
            payload = PushPayload.newBuilder()
                        .setPlatform(Platform.ios())
                        .setAudience(Audience.registrationId(token))
                        .setNotification(
                                Notification.newBuilder().addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(content)
                                .setBadge(bagde)
                                .setSound(sound)
                                .addExtras(extra)
                                .build())
                                .build())
                        //.setMessage(Message.content(JSON.toJSONString(custom)))
                        .setOptions(Options.newBuilder().setApnsProduction(true).build())
                        .build();

        }else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.registrationId(token))
                    .setNotification(
                            Notification.newBuilder().addPlatformNotification(IosNotification.newBuilder()
                                    .setAlert(content)
                                    .setBadge(bagde)
                                    .setSound(sound)
                                    .addExtras(extra)
                                    .build())
                                    .build())
                    //.setMessage(Message.content(JSON.toJSONString(custom)))
                    .build();
        }
        return payload;
    }



    public static PushPayload getPushPayloadByPushAllAndroid(String contentMessage) {
        //推送应用内消息
        //判断是开发环境还是生产环境
        PushPayload payload;
        if(sysEnv == 1) {
            //生产环境
            payload = PushPayload.newBuilder()
                        .setPlatform(Platform.android())
                        .setAudience(Audience.all())
                        .setMessage(Message.content(contentMessage))
                        .setOptions(Options.newBuilder().setApnsProduction(true).build())
                        .build();
        }else {
            payload = PushPayload.newBuilder()
                        .setPlatform(Platform.android())
                        .setAudience(Audience.all())
                        .setMessage(Message.content(contentMessage))
                        .build();
        }
        return payload;
    }

    public static PushPayload getPushPayloadByPushAllIos(String contentMessage) {
        //推送应用内消息
        //判断是开发环境还是生产环境
        PushPayload payload;
        if(sysEnv == 1) {
            //生产环境
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.all())
                    .setMessage(Message.content(contentMessage))
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())
                    .build();
        }else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.all())
                    .setMessage(Message.content(contentMessage))
                    .build();
        }
        return payload;
    }




    /**
     * @param jPushId
     * @param contentMessage
     * @param pushType
     * @return

     * 方法说明:定义极光推送类别 自定义(通知)推送
     * .setOptions(Options.newBuilder().setApnsProduction(true).build()  //表示是极光生产环境，不加上则默认开发环境

     * 创立日期:2018年4月14日 上午11:31:22
     * 创建人:yangcan

     */
    public static PushPayload buildPushSystemAllAlert(String jPushId,String contentMessage,String pushType) {
       if("message".equals(pushType)) {
            //推送自定义
            return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.registrationId(jPushId)).setMessage(
                    Message.content(contentMessage)).setOptions(Options.newBuilder().setApnsProduction(true).build()).build();
        }else {
           //推送通知
           return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.registrationId(jPushId)).setNotification(
                   Notification.newBuilder().addPlatformNotification(IosNotification.newBuilder()
                           .setAlert(contentMessage)
                           .autoBadge()
                           .setSound("default")
                           .build())
                           .build())
                            .build();
        }
    }

    public static PushResult pushSingleIosMessage(String token,Map<String,Object> custom,int platformType){
        try{
            //推送入参
            JPushClient jPushClient = getJPushClient(PushConstants.PUSH_IOS, platformType);
            if(jPushClient != null) {
                PushPayload payload = pushSingleIosMessageByPushPayload(token, custom);
                return jPushClient.sendPush(payload);
            }
        }catch (Exception e){
            logger.error("平台{},极光推送单个ios设备异常:{}",platformType,e);
        }
        return null;


    }

    public static PushPayload pushSingleIosMessageByPushPayload(String token,Map<String,Object> custom) {
        //推送应用内消息
        //判断是开发环境还是生产环境
        PushPayload payload;
        if(sysEnv == 1) {
            //生产环境
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.registrationId(token))
                    .setMessage(Message.content(JSON.toJSONString(custom)))
                    .setOptions(Options.newBuilder().setApnsProduction(true).build())
                    .build();

        }else {
            payload = PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.registrationId(token))
                    .setMessage(Message.content(JSON.toJSONString(custom)))
                    .build();
        }
        return payload;
    }


    public static void main(String[] args) throws Exception {
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("type", "NOTIFY_MESSAGE");
        messageMap.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("pushMessageId", "sconPushMessage.getId()");
        dataMap.put("title", "sconPushMessage.getTitle()");
        dataMap.put("vipId", "vipId");
        dataMap.put("content", "八风吹不动，端坐紫金莲。出生确定起点，选择决定方向，心态左右生活。能左右我们生活的，永远是自己。");
        dataMap.put("createTime", DateUtil.format_yyyyMMddHHmmss(new Date()));
        messageMap.put("data", dataMap);

//        Map<String, String> extra = JSON.parseObject(JSON.toJSONString(messageMap),new TypeReference<Map<String,String>>(){});
//        System.out.println(messageMap);
//        System.out.println(extra);

//        PushResult result = JiGuangPushUtils.pushByIos("1a1018970a33d9dd5a8", "测试角标(通知)消息体111", 2, null, messageMap,2,99);
//        System.out.println("Got result - " + result);

        Map<String, Object> messageMap2 = new HashMap<>();
        messageMap2.put("type", "WIFI_INFO");
        messageMap2.put("time", DateUtil.format_yyyyMMddHHmmss(new Date()));
        Map<String, Object> dataMap2 = new HashMap<>();
        dataMap2.put("wifiName", "aijia");
        dataMap2.put("password", "12345678");
        dataMap2.put("type", "1");
        messageMap2.put("data", dataMap2);

//        PushResult result = MessagePushUtils.pushByAndroid("140fe1da9e3adf29ac1", "私塾家", JSON.toJSONString(messageMap), 2, "message", null);
//        System.out.println("Got result - " + result);

        PushResult result = MessagePushUtils.pushByAndroid("190e35f7e0d31990271", "私塾家", JSON.toJSONString(messageMap), 6, "message", null);
        System.out.println("Got result - " + result);
    }

}
