package com.ym.game.notif;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;

import com.ym.ddhy.R;
import com.ym.game.GameActivity;
import com.ym.library.utils.LogUtils;
import java.lang.reflect.Method;


public class NotificationService extends Service {
    private Context context;
    private RemoteViews NormalView;
    private Notification notification;
    public final static int ID_FOR_CUSTOM_VIEW = 7;

    private ActionReceiver receiver = new ActionReceiver();
    public final static String NOTIFICATION_GET_FRUIT = "com.smile.notification.getfruit";
    private static String TAG = "NotificationService";
    private NotificationManager mNotificationManager;

    public class MyBinder extends Binder {
        public NotificationService getService() {
            return NotificationService.this;
        }
    }

    //通过binder实现调用者client与Service之间的通信
    private MyBinder binder = new MyBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    public static void startNotificationService(Context ctx) {
        try {
//            Boolean isOpen = (Boolean) SPUtils.get(ctx, SPUtils.SP_LONG_NOTICATION, true);
//            if (!isOpen) {
//                return;
//            }
            //开启常驻通知栏
            Intent intent3 = new Intent(ctx, NotificationService.class);
            ctx.startService(intent3);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

        context = getApplicationContext();
        initNotification();
        IntentFilter filter = new IntentFilter();
        filter.addAction(NOTIFICATION_GET_FRUIT);
        registerReceiver(receiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        updateNotivView();
        if (notification != null) {
            mNotificationManager.notify(ID_FOR_CUSTOM_VIEW, notification);
        }
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (receiver != null)
            unregisterReceiver(receiver);
    }

    private void initNotification() {
        if (mNotificationManager == null) {
            mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        PendingIntent getFruitIntent = PendingIntent.getBroadcast(context, (int) System.currentTimeMillis(), new Intent(NOTIFICATION_GET_FRUIT), PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, createNotificationChannel(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.setSmallIcon(R.mipmap.icon_launch)
                    .setContentTitle(context.getString(R.string.app_name))
                    .setContentText(context.getString(R.string.app_name))
                    .setTicker(context.getString(R.string.app_name))
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setWhen(System.currentTimeMillis())
                    .setGroupSummary(true)
                    .setGroup("group")
                    .setOngoing(true);

        } else {
            builder.setSmallIcon(R.mipmap.icon_launch)
                    .setContentTitle(context.getString(R.string.app_name))
                    .setContentText(context.getString(R.string.app_name))
                    .setTicker(context.getString(R.string.app_name))
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setWhen(System.currentTimeMillis())
                    .setOngoing(true);
        }
        //Couldn't expand RemoteViews
        try {
            updateNotivView();
            builder.setCustomContentView(NormalView);
            NormalView.setOnClickPendingIntent(R.id.id_notification_click, getFruitIntent);
            notification = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        startForeground(ID_FOR_CUSTOM_VIEW, notification);
//        Boolean isOpen = (Boolean) SPUtils.get(context, SPUtils.SP_LONG_NOTICATION, true);
        Boolean isOpen = true;
        try {
            if (isOpen) {
                if (notification != null) {
                    startForeground(ID_FOR_CUSTOM_VIEW, notification);
                }
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "set service for push exception: ", e);
        }
    }

    private void updateNotivView() {
        //Couldn't expand RemoteViews
        try {
            if (NormalView == null) {
                NormalView = new RemoteViews(context.getPackageName(), R.layout.notification_view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ActionReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent data) {
            if (data == null || data.getAction() == null) {
                return;
            }
//            collapseStatusBar(context);
            collapseStatusBar();
            switch (data.getAction()) {
                case NOTIFICATION_GET_FRUIT:
                    Intent intent2 = new Intent(context, GameActivity.class);
                    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent2);
                    break;
                default:
                    break;
            }
        }
    }

    //9.0通知栏  适配
    public static String createNotificationChannel(Context context) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "luck_farm";
            CharSequence channelName = "幸运农场";
            String channelDescription = "快速收获";
            int channelImportance = NotificationManager.IMPORTANCE_MIN;

            NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
            // 设置描述 最长30字符
            notificationChannel.setDescription(channelDescription);
            // 该渠道的通知是否使用震动
            notificationChannel.enableVibration(false);
            // 设置显示模式
            notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);

            NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);

            return channelId;
        } else {
            return null;
        }
    }

    public void collapseStatusBar(Context context) {
        try {
            @SuppressLint("WrongConstant") Object statusBarManager = context.getSystemService("statusbar");
            Method collapse;
            if (Build.VERSION.SDK_INT <= 16) {
                collapse = statusBarManager.getClass().getMethod("collapse");
            } else {
                collapse = statusBarManager.getClass().getMethod("collapsePanels");
            }
            collapse.invoke(statusBarManager);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

    public  void collapseStatusBar() {
        @SuppressLint("WrongConstant") Object service =getSystemService("statusbar");
        if (null == service)
            return;
        try {
            Class<?> clazz = Class.forName("android.app.StatusBarManager");
            int sdkVersion = android.os.Build.VERSION.SDK_INT;
            Method collapse = null;
            if (sdkVersion <= 16) {
                collapse = clazz.getMethod("collapse");
            } else {
                collapse = clazz.getMethod("collapsePanels");
            }
            collapse.setAccessible(true);
            collapse.invoke(service);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
