package  com.example.mydemo.strategy.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
import android.os.Build
import android.os.IBinder
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.IconCompat
import com.base.locationsharewhite.helper.ConstConfig
import com.base.locationsharewhite.helper.GoogleSdkMgr
import com.example.mydemo.MainActivity
import com.example.mydemo.R


/**
 *  常驻通知栏
 */
class StayNotificationService : Service() {

    private val TAG = "StayNotificationService"

    companion object {

        var isRunning = false

        fun Context.startStayNotification() {
            if (isRunning) return

            val intent = Intent(this, StayNotificationService::class.java)
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
                return
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
        }

        fun Context.restartStartStayNotification() {
            val intent = Intent(this, StayNotificationService::class.java)
            stopService(intent)

            startStayNotification()
        }


        fun createPermanentNotification(context: Context): Notification {

            val channelName = "Permanent Foreground Service Channel"
            val channelId = "permanent_channel"
            val contentView = RemoteViews(context.packageName, R.layout.stay_notification_big)
            val expendView = RemoteViews(context.packageName, R.layout.stay_notification_big)


            val builder = NotificationCompat.Builder(context, channelId)
            val smallIcon = IconCompat.createFromIcon(
                context, Icon.createWithResource(
                    context, ConstConfig.NOTIFICATION_LOGO
                )
            )

            smallIcon?.let {
                builder.setSmallIcon(smallIcon) //设置状态栏内的小图标
            }

            val nfIntent = Intent(context, MainActivity::class.java)
            val pendingIntent =
                PendingIntent.getActivity(context, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE)
            builder.setLargeIcon(
                BitmapFactory.decodeResource(
                    context.resources,
                    ConstConfig.NOTIFICATION_LOGO
                )
            )
            builder.setContentTitle(context.resources.getString(R.string.app_name))
            builder.setContentIntent(pendingIntent) //设置PendingIntent
            builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE) //设置通知公开可见
            builder.setAutoCancel(false)
            builder.setOngoing(true)
            builder.setPriority(NotificationCompat.PRIORITY_MAX) //优先级为：重要通知
            builder.setWhen(System.currentTimeMillis())
            builder.setCustomContentView(contentView)
            builder.setCustomBigContentView(expendView)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel =
                    NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW)
                channel.lockscreenVisibility = 1
                val notificationManager =
                    context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                notificationManager.createNotificationChannel(channel)
                builder.setChannelId(channelId)
            }
            return builder.build()
        }

    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        //LogEx.logDebug(TAG, "onStartCommand intent=$intent")
        if (intent == null) {
            // EventUtils.event("onStartCommand", "Foreground System auto launch intent=null isRunning=$isRunning")
            return START_NOT_STICKY
        }
        if (!isRunning) {
            //  LogEx.logDebug(TAG, "onStartCommand startForeground")
            startForeground()

            isRunning = true
        }

        return START_STICKY
    }

    private fun startForeground() {
        val notification = createPermanentNotification(GoogleSdkMgr.context)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(
                ConstConfig.NOTIFICATION_PERMANENT_ID,
                notification,
                ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
            )
        } else {
            startForeground(ConstConfig.NOTIFICATION_PERMANENT_ID, notification)
        }
        isRunning = true
    }


    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        isRunning = false
        super.onDestroy()
    }
}