package com.jeeplus.common.utils;

import cn.jpush.api.JPushClient;
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.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.schedule.ScheduleResult;
import com.easemob.server.example.api.impl.EasemobIMUsers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 极光推送工具类
 * 
 * @author yangfan
 * @version 2017-8-1
 */


public class JPushClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(JPushClientUtil.class);
	//static String appKey = "50deb4032691dca76b445e25";
	//static String masterSecret = "65d3be2c5fe8b352004f63a7";
//	static String appKey = "a4378a0373412f39bf6fb4b5";
//	static String masterSecret = "7aa1eb136050f7a395521214";
    static String appKey ="b9596dea64c5ee1b143494eb";
    static String masterSecret ="d04a9854eb26a0540ff02835";

//	static int timeToLive = 864000;
	static JPushClient jpush = new JPushClient(masterSecret, appKey);

	/**
	 * 发送通知给全员
	 * @param title 通知标题，必须
	 * @param content 通知内容，必须
	 * @param extras 附加内容，可以为空
	 * @return 推送结果成功为true
	 */
	public static boolean sendNotificationToAll(String title, String content, Map extras) {
		boolean ret = false;
		try {
			Builder builder = PushPayload.newBuilder().setPlatform(Platform.android()).setNotification(Notification.android(content, title, extras)).setAudience(Audience.all()); 
			try {
				jpush.sendPush(builder.build());
				ret = true;
			} catch(Exception e) { 
			}
			builder = PushPayload.newBuilder().setPlatform(Platform.ios()).setAudience(Audience.all());
			builder.setNotification(Notification.newBuilder().addPlatformNotification(IosNotification.newBuilder().setAlert(content).autoBadge().addExtras(extras).setSound("default").setBadge(1).setContentAvailable(true).setSound("default").build()).build());
//			builder.setAudience(Audience.registrationId("0012d749fe5", "081f90d0e0e")); 
			jpush.sendPush(builder.build());
			ret = true;
		} catch (Exception e) { 
		}
		return ret;
    }
	/**
	 * 发送通知给Android 或 IOS
	 * @param title 通知标题，必须
	 * @param content 通知内容，必须
	 * @param extras 附加内容，可以为空
	 * @return 推送结果成功为true
	 */
	public static boolean sendNotificationTo_Android_or_IOS(String remarks,String title, String content, Map extras) {
		boolean ret = false;
		Builder  builder = null ;
		try {
			if("android".equals(remarks.toLowerCase())){

				builder = PushPayload.newBuilder().setPlatform(Platform.android()).setNotification(Notification.android(content, title, extras)).setAudience(Audience.all());
			}else if("ios".equals(remarks.toLowerCase())){

				builder = PushPayload.newBuilder().setPlatform(Platform.ios()).setAudience(Audience.all());
				builder.setNotification(Notification.newBuilder().addPlatformNotification(IosNotification.newBuilder().setAlert(content).autoBadge().addExtras(extras).setSound("default").setBadge(1).setContentAvailable(true).setSound("default").build()).build());
			}

			jpush.sendPush(builder.build());
			ret = true;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
    /**
     * 发送通知到别名，别名由客户端登录后设置成用户账号
	 * @param title 通知标题，必须
	 * @param content 通知内容，必须
	 * @param extras 附加内容，可以为空
	 * @return 推送结果成功为true
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean sendNotificationToAliases(String title, String content, Map extras, List aliases) {
		List list = new ArrayList();
		for (Object id :aliases){
			Jedis jedis = null;
			try {
				jedis = JedisUtils.getResource();
				String userId = jedis.get(id.toString());
				if (StringUtils.isNotBlank(userId)){
					list.add(id);
				}
			} catch (Exception e) {
				logger.error("getActiveSessions", e);
			} finally {
				JedisUtils.returnResource(jedis);
			}
		}

		boolean ret = true;
		try {
			if(null == aliases || aliases.size() < 1) {
				return false;
			}
			if(null == title || title.length() < 1) {
				return false;
			}
			if(null == content || content.length() < 1) {
				return false;
			}
			Builder builder = PushPayload.newBuilder().setPlatform(Platform.android()).setNotification(Notification.android(content, title, extras)).setAudience(Audience.alias(list));
			try {
				jpush.sendPush(builder.build());
				ret = true;
			} catch(Exception e) {

			}
			builder = PushPayload.newBuilder().setPlatform(Platform.ios()).setAudience(Audience.alias(list));
			builder.setNotification(Notification.newBuilder().setAlert(content).addPlatformNotification(IosNotification.newBuilder().addExtras(extras).autoBadge().setSound("default").setBadge(1).setContentAvailable(true).setSound("default").build()).build());
			jpush.sendPush(builder.build());
			ret = true;
		} catch (Exception e) {
		}
		return ret; 
	}
	/**
	 * 发送通知到别名，别名由客户端登录后设置成用户账号
	 * @param title 通知标题，必须
	 * @param content 通知内容，必须
	 * @param extras 附加内容，可以为空
	 * @return 推送结果成功为true
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String,Object> sendNotificationToAliasesMap(String title, String content, Map extras, List aliases) {
		Map<String,Object> map = new HashMap<>();
		List list = new ArrayList();
		List returnList = new ArrayList();
		logger.info("---------------------");
		logger.info("aliases="+aliases.toString());
		for (Object id :aliases){
			Jedis jedis = null;
			try {
				jedis = JedisUtils.getResource();
				String userId = jedis.get(id.toString());
				logger.info("-----user:"+userId);
				if (StringUtils.isNotBlank(userId)){
					list.add(id);
				}
			} catch (Exception e) {
				logger.error("getActiveSessions", e);
			} finally {
				JedisUtils.returnResource(jedis);
			}
		}
		logger.info("---------------------");

		boolean ret = true;
		try {
			if(null == list || list.size() < 1) {
				map.put("status","false");
				return map;
			}
			if(null == title || title.length() < 1) {
				map.put("status","false");
				return map;
			}
			if(null == content || content.length() < 1) {
				map.put("status","false");
				return map;
			}
			Builder builder = PushPayload.newBuilder().setPlatform(Platform.android()).setNotification(Notification.android(content, title, extras)).setAudience(Audience.alias(list));
			try {
				jpush.sendPush(builder.build());
			} catch(Exception e) {

			}
			builder = PushPayload.newBuilder().setPlatform(Platform.ios()).setAudience(Audience.alias(list));
			builder.setNotification(Notification.newBuilder().setAlert(content).addPlatformNotification(IosNotification.newBuilder().addExtras(extras).autoBadge().setSound("default").setBadge(1).setContentAvailable(true).setSound("default").build()).build());
			jpush.sendPush(builder.build());
		} catch (Exception e) {
		}
		map.put("list",returnList);
		map.put("status","true");
		return map;
	}
	/**
	 * 发送通知到别名数组，别名由客户端登录后设置成用户账号
	 * @param title 通知标题，必须
	 * @param content 通知内容，必须
	 * @param extras 附加内容，可以为空
	 * @return 推送结果成功为true
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static boolean sendNotificationToAlias(String title, String content, Map extras, String alias) {
		if(null == alias || alias.length() < 1) {
			return false;
		}
		ArrayList aliases = new ArrayList();
		aliases.add(alias);  
		return sendNotificationToAliases(title, content, extras, aliases);
	}
    /**
     * 定时发送
     * @param title 通知标题，必须
     * @param content 通知内容，必须
     * @param extras 附加内容，可以为空
     * @return 推送结果成功为true
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static boolean sendNotificationToAliasByTime(String title, String content, Map extras, String alias,String time) {
        if(null == alias || alias.length() < 1) {
            return false;
        }
        ArrayList aliases = new ArrayList();
        aliases.add(alias);
        return sendNotificationToAliasesByTime(title, content, extras, aliases, time);
    }

    /**
     * 定时发送
     * @param title 通知标题，必须
     * @param content 通知内容，必须
     * @param extras 附加内容，可以为空
     * @return 推送结果成功为true
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static boolean sendNotificationToAliasesByTime(String title, String content, Map extras, List aliases,String time) {
        boolean ret = true;
        try {
            if(null == aliases || aliases.size() < 1) {
                return false;
            }
            if(null == title || title.length() < 1) {
                return false;
            }
            if(null == content || content.length() < 1) {
                return false;
            }
            PushPayload push = JPushClientUtil.buildPushObject_android_ios_alias_alert(title,content,extras,aliases);
            ScheduleResult result = jpush.createSingleSchedule(content, time, push);

            System.err.println("==================推送调度====================");
            logger.info("schedule result is " + result);
            ret = true;
        } catch (Exception e) {
        }
        return ret;
    }

    /**
     * 生成极光推送对象PushPayload（采用java SDK）
     * @param alias
     * @param content
     * @return PushPayload
     */
    public static PushPayload buildPushObject_android_ios_alias_alert(String title, String content, Map extras,List alias){
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtras(extras)
                                .setAlert(content)
                                .setTitle(title)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtras(extras)
                                .setAlert(content)
                                .addExtras(extras)
								.setBadge(1)
								.setSound("default")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }

	public static void main(String [] args) throws  Exception{
		Map extras = new HashMap();
        String title ="标题" ;
        String content="测试一下丨测试推送丨排除异常" ;
		extras.put("233", "233");
        String aliase = "93d543eb589647c5a96b69236a613cf3";
        String time = "2017-12-08 10:33:30";
        logger.error("time="+time.substring(0,7));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        logger.error("date="+date);
        String x = "1234";
        int y = x.indexOf("|");
        logger.info(y+"233");
		SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
		String sqltime = "9:1";
		Date d = sdf1.parse(sqltime);
		String dz = sdf1.format(d);
		logger.info("dz="+dz+",d"+d);
		String enname1 = StringUtils.getPinYinHeadChar("我是谁", 2) + "gly";
		String enname2 = StringUtils.getPinYinHeadChar("我是谁", 2) + "gly";
		String enname3 = StringUtils.getPinYinHeadChar("我是谁", 1) + "gly";
		String enname4 = StringUtils.getPinYinHeadChar("我是税", 1) + "gly";
		logger.info("enname1="+enname1+","+"enname2="+enname2+","+"enname3="+enname3+","+"enname4="+enname4);
     /*   JPushClientUtil.sendNotificationToAliasByTime(title, content, extras, aliase, time);
		boolean b = JPushClientUtil.sendNotificationToAlias(title,content,extras,aliase);
		System.err.println(b);*/
		/*boolean e = JPushClientUtil.sendNotificationToAll(title,content,extras);
		System.err.println(b+","+e);
		boolean c = JPushClientUtil.sendNotificationTo_Android_or_IOS("android",title,content,extras);
		System.err.println(b+","+c);

		System.err.println(b+","+c+","+e);*/
	}

   /* public static void main(String[] args) {
        Map<String, Object> map = new LinkedHashMap<String,Object>();
        map.put("username","zhaokuo");
        map.put("password", "123456");
        map.put("email", "zhaokuo719@163.com");
        map.put("sex", "男");
        //第一种 用for循环的方式
        for (Map.Entry<String, Object> m :map.entrySet())  {
            System.out.println(m.getKey()+"\t"+m.getValue());
        }
        //利用迭代 （Iterator）
        Set set=map.entrySet();
        Iterator iterator=set.iterator();
        while(iterator.hasNext()){
            Map.Entry<String, Object> enter=(Map.Entry<String, Object>)
                    iterator.next();
            System.out.println(enter.getKey()+"\t"+enter.getValue());
        }
        //利用KeySet 迭代
        Iterator it = map.keySet().iterator();
        while(it.hasNext()){
            String key;
            String value;
            key=it.next().toString();
            value=(String) map.get(key);
            System.out.println(key+"--"+value);
        }
        //利用EnterySet迭代
        Iterator i=map.entrySet().iterator();
        System.out.println( map.entrySet().size());
        String key;
        String value;
        while(i.hasNext()){
            Map.Entry entry = (Map.Entry)i.next();
            key=entry.getKey().toString();
            value=entry.getValue().toString();
            System.out.println(key+"===="+value);
        }
        System.out.println("233---"+getKeyByValue(map, "zhaokuo"));
    }*/
    public static String getKeyByValue(Map map, Object value) {
        String keys="";
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object obj = entry.getValue();
            if (obj != null && obj.equals(value)) {
                keys=(String) entry.getKey();
            }

        }
        return keys;
    }


}
