package com.sheep.gamegroup.receiver;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.view.activity.MiddleAct;
import com.sheep.jiuyan.samllsheep.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.Random;

import cn.jpush.android.api.JPushInterface;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * Created by realicing on 2018/5/9.
 * realicing@sina.com
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class SheepJpushReceiver extends BroadcastReceiver {
    private static final String TAG = "JIGUANG-SmallSheep";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Log.d(TAG, "[SheepJpushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Log.d(TAG, "[SheepJpushReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {//自定义消息中有自定义字段时才会接收到，且不会有通知
                Log.d(TAG, "[SheepJpushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                processCustomMessage(context, bundle, intent.getIntExtra(JPushInterface.EXTRA_MSG_ID, new Random().nextInt(113920)));

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {//除了自定义消息中有自定义字段的消息，都会接收到通知
                Log.d(TAG, "[SheepJpushReceiver] 接收到推送下来的通知");
                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                Log.d(TAG, "[SheepJpushReceiver] 接收到推送下来的通知的ID: " + notifactionId);

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Log.d(TAG, "[SheepJpushReceiver] 用户点击打开了通知");
                //打开自定义的Activity
                Jump2View.getInstance().newTaskTopStartAct(context, MiddleAct.class, bundle);

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Log.d(TAG, "[SheepJpushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Log.w(TAG, "[SheepJpushReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Log.d(TAG, "[SheepJpushReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    /**
     * 处理自定义消息
     * @param context
     * @param bundle
     * @param msgId
     * @throws JSONException
     */
    private void processCustomMessage(Context context, Bundle bundle, int msgId) throws JSONException {
//        JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
//        String msg = json.optString("msg");
//        String title = json.optString("title");
//        String id = "my_channel_01";
//        String name = context.getString(R.string.app_name);
//        NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
//        if(notificationManager != null) {
//            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, id)
//                    .setContentTitle(title)
//                    .setContentText(msg);
//            Notification notification;
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
//                notificationManager.createNotificationChannel(mChannel);
//            } else {
//                notificationBuilder.setOngoing(true);
//            }
//            notification = notificationBuilder.build();
//            notificationManager.notify(msgId, notification);
//        }
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (mNotificationManager != null) {
            String appName = context.getString(R.string.app_name);
            String summaryText = "来自"+appName;
            JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
            String msg = json.optString("msg");
            String title = json.optString("title");
            //为了版本兼容  选择V7包下的NotificationCompat进行构造
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, String.valueOf(msgId));
            //点击通知栏跳转到相应的应用里面
            Intent notificationIntent = new Intent(context, MiddleAct.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            notificationIntent.putExtras(bundle);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            notificationBuilder
                    //下拉显示的大图标
    //                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon))
    //                .setSmallIcon(R.mipmap.remenyx)//系统状态栏显示的小图标 remenyx
                    .setSmallIcon(R.drawable.icon)
                    .setWhen(System.currentTimeMillis())
                    .setTicker(title)//Ticker是状态栏显示的提示
                    .setDefaults(NotificationCompat.DEFAULT_ALL);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notificationBuilder.setContentTitle(appName)//第一行内容  通常作为通知栏标题
                        .setOngoing(true)//禁止滑动删除
                        .setContentText(title);//第二行内容 通常是通知正文
                NotificationChannel mChannel = new NotificationChannel(String.valueOf(msgId), appName, NotificationManager.IMPORTANCE_HIGH);
                mNotificationManager.createNotificationChannel(mChannel);
            } else {
                notificationBuilder.setContentTitle(appName)//第一行内容  通常作为通知栏标题
                        .setContentText(title);//第二行内容 通常是通知正文
                if (!TextUtils.isEmpty(msg)) {
                    notificationBuilder.setSubText(msg);//第三行内容 通常是内容摘要什么的 在低版本机器上不一定显示
                    notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).setSummaryText(summaryText).bigText(msg));
                } else {
    //           notificationBuilder.setSubText("subText");
                    //添加宽视图
                    NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
                    style.setBigContentTitle(title);
                    //由手机屏幕像素决定显示多少
    //          style.addLine("line1");
    //          style.addLine("line2");
                    style.setSummaryText(summaryText);//添加概要
                    notificationBuilder.setStyle(style);
                }
            }
            notificationBuilder.setPriority(Notification.PRIORITY_MAX).setContentIntent(pendingIntent);//点击跳转的intent
            Notification notification = notificationBuilder.build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(msgId, notification);
        }
    }
}
