package com.base.utils.tools.android;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.base.utils.receive.NotificationBroadcastReceiver;

/**
 * 通知栏工具
 */
public class NotificationUtil {
    public static final String TYPE = "type"; //这个type是为了Notification更新信息的，这个不明白的朋友可以去搜搜，很多
    public final static String NOTIFICATION_ACTION_CLICK = "notification_clicked";     //广播会根据此Action识别
    public final static String NOTIFICATION_ACTION_DELETE = "notification_cancelled";  //广播会根据此Action识别

    /**
     * 传送上下文
     */
    private Context mContext;
    /**
     * 通知栏窗口管理器
     */
    private static NotificationManager mNotificationManager;


    /**
     * 响铃3秒内不重复
     */
    private static long mIntervalRingTime = 3 * 1000;
    private static long mLongLastTime;
    private final static long mDelayClearTime = 2 * 1000;       //用于延迟清除通知栏消息的 时间

    /**
     * 是否自动区分收到通知时app前后台处理：
     * 当处于后台时：设置状态栏显示信息
     * 当处于前台时：设置信息2秒后，信息自动消失
     */
    private static boolean mAppIsDistinguishForeGround = true;

    private NotificationUtil(Context context) {
        this.mContext = context;
        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    }
    private static NotificationUtil instance;
    public synchronized static NotificationUtil getInstance(Context context){
        if (instance==null){
            instance = new NotificationUtil(context);
        }
        return instance;
    }
    public void  onDestroy(){
        clearAllNotify();
        instance=null;
        mNotificationManager = null;
    }

    /**
     * 设置间隔时间
     *
     * @param intervalRingTime
     */
    public void setIntervalRingTime(long intervalRingTime) {
        mIntervalRingTime = intervalRingTime;
    }

    /**
     * 设置是否区分前后台
     *
     * @param isDistinguishForeGround 是否区分前后台
     *                                是否自动区分收到通知时app前后台处理：
     *                                当处于后台时：设置状态栏显示信息
     *                                当处于前台时：设置信息0.8秒后信息自动消失
     */
    public void setDistinguishForeGround(boolean isDistinguishForeGround) {
        mAppIsDistinguishForeGround = isDistinguishForeGround;
    }

    /**
     * 设置状态栏显示信息
     *
     * @param resId       图标（本地）
     * @param tickerText  消息内容(状态栏顶部自动显示)
     * @param title       消息来源标题
     * @param text        消息内容(下拉菜单显示)
     * @param notifyId 推送消息类型(相当于每个通知栏消息的id)
     */
    public void setNotify(int resId, String tickerText, String title, String text, int notifyId) {

        if (mAppIsDistinguishForeGround && !ActivityUtil.appIsBackground(mContext)) {
            showDelayClearNotify(resId, tickerText, title, text);
        } else {
            showNormalNotify(resId, tickerText, title, text, notifyId);
        }
    }

    /**
     * 设置状态栏显示信息
     *
     * @param resId       图标（本地）
     * @param tickerText  消息内容(状态栏顶部自动显示)
     * @param title       消息来源
     * @param text        消息内容(下拉菜单显示)
     * @param notifyId   推送消息的id
     *
     *                    int flags 有：
     *                    PendingIntent.
     *                    FLAG_CANCEL_CURRENT   取消当前
     *                    FLAG_IMMUTABLE        不可变的
     *                    FLAG_UPDATE_CURRENT   更新当前的
     *                    FLAG_NO_CREATE        不创建
     *                    FLAG_ONE_SHOT
     */
    public void showNormalNotify(int resId,
                                 String tickerText,
                                 String title,
                                 String text,
                                 int notifyId) {

        Intent intentClick = new Intent(mContext, NotificationBroadcastReceiver.class);
        intentClick.setAction(NOTIFICATION_ACTION_CLICK);
        intentClick.putExtra(TYPE, notifyId);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(mContext, notifyId, intentClick, PendingIntent.FLAG_ONE_SHOT);

        Intent intentCancel = new Intent(mContext, NotificationBroadcastReceiver.class);
        intentCancel.setAction(NOTIFICATION_ACTION_DELETE);
        intentCancel.putExtra(TYPE, notifyId);
        PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(mContext, notifyId, intentCancel, PendingIntent.FLAG_ONE_SHOT);


        //Intent intent = new Intent(mContext, mIntentActivityClass);
        /*
         对PendingIntent.getActivity(Context context, int requestCode, Intent intent, int flags)参数进行下分析，
         重点是第二跟第四个：
         requestCode，这个参数就是用来区分不同的通知，例如这个通知是属于A用户的，那么就得传入A的唯一标识。
         flags，使用PendingIntent.FLAG_UPDATE_CURRENT即可，更新同一个requestCode的PendingIntent的数据。
         最后在发通知的时候，
         调用NotificationManager.notify(int id, Notification notification)，第一个参数也是传入某个用户的唯一标识。
         这样才能达到预期效果。
         * */
        //PendingIntent pendingIntent = PendingIntent.getActivity(mContext, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        long[] vibrate = {0, 100, 200, 300};
        Notification.Builder builder = new Notification.Builder(mContext)
                .setSmallIcon(resId)
                .setTicker(tickerText)
                .setContentTitle(title)
                .setContentText(text)
                .setContentIntent(pendingIntentClick)
                .setDeleteIntent(pendingIntentCancel);
        if (System.currentTimeMillis() - mLongLastTime > mIntervalRingTime) {
            builder.setVibrate(vibrate);
            builder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND);
            mLongLastTime = System.currentTimeMillis();
        }
        Notification notify = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            notify = builder.build();
        } else if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            notify = builder.getNotification();
        }
        if (notify != null) {
            notify.flags |= Notification.FLAG_AUTO_CANCEL;          // FLAG_AUTO_CANCEL表明当通知被用户点击时，通知将被清除。
            mNotificationManager.notify(notifyId, notify);
        }
    }

    /**
     * 设置信息0.8秒后信息自动消失
     *
     * @param tickerText 消息内容(状态栏顶部自动显示)
     * @param title      消息来源
     * @param text       消息内容(下拉菜单显示)
     */
    public void showDelayClearNotify(int resId,
                                     String tickerText,
                                     String title,
                                     String text
    ) {
        String time = String.valueOf(System.currentTimeMillis());
        final int notifyId = Integer.parseInt(time.substring(time.length() - 6, time.length()));  //使用当前时间的前几位用来做id
        Intent intentClick = new Intent(mContext, NotificationBroadcastReceiver.class);
        intentClick.setAction(NOTIFICATION_ACTION_CLICK);
        intentClick.putExtra(TYPE, notifyId);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(mContext, notifyId, intentClick, PendingIntent.FLAG_ONE_SHOT);

        Intent intentCancel = new Intent(mContext, NotificationBroadcastReceiver.class);
        intentCancel.setAction(NOTIFICATION_ACTION_DELETE);
        intentCancel.putExtra(TYPE, notifyId);
        PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(mContext, notifyId, intentCancel, PendingIntent.FLAG_ONE_SHOT);

//        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, notifyId,
//                new Intent(mContext, mIntentActivityClass), PendingIntent.FLAG_UPDATE_CURRENT);
        long[] vibrate = {0, 100, 200, 300};
        Notification.Builder builder = new Notification.Builder(mContext)
                .setSmallIcon(resId)
                .setTicker(tickerText)
                .setContentTitle(title)
                .setContentText(text)
                .setContentIntent(pendingIntentClick)
                .setDeleteIntent(pendingIntentCancel);
        if (System.currentTimeMillis() - mLongLastTime > mIntervalRingTime) {
            builder.setVibrate(vibrate);
            builder.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND);
            mLongLastTime = System.currentTimeMillis();
        }
        Notification notify = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            notify = builder.build();
        } else if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            notify = builder.getNotification();
        }
        if (notify != null) {
            notify.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时，通知将被清除。
            mNotificationManager.notify(notifyId, notify);
            /** 设置1秒后自动消失信息 */
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(mDelayClearTime);
                        mNotificationManager.cancel(notifyId);// 取消显示该条信息
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    /**
     * 清除所有通知
     */
    public void clearAllNotify() {
        if (mNotificationManager != null) {
            mNotificationManager.cancelAll();
        }
    }
}
