package com.quyunshuo.module.home.service

import ZtlApi.ZtlManager
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.AlarmManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.Process
import android.util.Log
import android.view.WindowManager
import com.elvishew.xlog.XLog
import com.hboxs.serialport.plc.DialogClickListener
import com.hboxs.serialport.sbc.SBCHeartbeat.initIsSuccess
import com.hboxs.serialport.sbc.VBoxMessage
import com.hboxs.serialport.sbc.VboxSerialPortDevice
import com.hboxs.serialport.sbc.VboxSerialPortManager
import com.hjq.http.lifecycle.LifecycleService
import com.module.pay.common.PayAgreementUtil
import com.module.pay.nayax.CreditCardPresenter
import com.module.pay.strategy.PaySendDataFactory
import com.quyunshuo.androidbaseframemvvm.base.BaseApplication
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.constant.MqName
import com.quyunshuo.androidbaseframemvvm.common.constant.event.ApiMessageEvent
import com.quyunshuo.androidbaseframemvvm.common.util.LogUtil
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import com.quyunshuo.module.home.activity.main.MainActivity
import com.quyunshuo.module.home.dialog.CountDownDialogFragment
import com.quyunshuo.module.home.dialog.WarringDialog
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

/**
 * 强制返回App服务：用与解决闪退自回复的功能
 */
@AndroidEntryPoint
class ForceBackToAppService : LifecycleService() {
    private val TAG = "GlobalService"

    private val NOTIFICATION_ID = "1"
    private val NOTIFICATION_NAME: CharSequence = "GlobalService"
    //强制返回App的携程
    var forceBackToAppJob: Job? = null

    //这个必须加，不能设置为null
    private fun getNotification(): Notification {
        val builder: Notification.Builder = Notification.Builder(this)
            .setContentTitle("GlobalService")
            .setContentText("我正在运行") //标题和内容可以不加
        //设置Notification的ChannelID,否则不能正常显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(NOTIFICATION_ID)
        }
        val notification = builder.build()
        return notification
    }


    @SuppressLint("ForegroundServiceType")
    override fun onCreate() {
        super.onCreate()
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        //创建NotificationChannel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                NOTIFICATION_ID,
                NOTIFICATION_NAME,
                NotificationManager.IMPORTANCE_HIGH
            )
            notificationManager.createNotificationChannel(channel)
            startForeground(1, getNotification())
        }
        XLog.init()
        forceBackToApp()
    }

    /**
     * 强制跳回App
     */
    fun forceBackToApp() {
        if (forceBackToAppJob == null) {
            forceBackToAppJob = CoroutineScope(Dispatchers.IO).launch {
                while (isActive) {//在协程中使用 isActive 可以确保协程在取消时能够及时退出循环或停止任务，避免资源浪费。
                    delay(10000)
                    //判断程序是否在运行
                    val isRunning: Boolean = isServiceStarted(
                        BaseApplication.context,
                        "com.quyunshuo.androidbaseframemvvm"
                    )
                    XLogUtil.d("MyTestService,Build.MODEL onReceive:程序未开启============$isRunning")
                    //运行中，跳过他。
                    if (isRunning) {
                        continue
                    }
                    val intent: Intent = Intent(
                        BaseApplication.context,
                        MainActivity::class.java
                    ) //此处我是根据需要重新启动时先进入欢迎页
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) //关掉所要到的界面中间的activity

                    @SuppressLint("WrongConstant") val restartIntent = PendingIntent.getActivity(
                        BaseApplication.context, 0, intent,
                        Intent.FLAG_ACTIVITY_NEW_TASK or PendingIntent.FLAG_IMMUTABLE
                    )

                    //退出程序
                    val mgr = BaseApplication.context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
                    mgr[AlarmManager.RTC, System.currentTimeMillis() + 1000] =
                        restartIntent // 1秒钟后重启应用，这个可以根据需要自己定义

                    //干掉当前的程序
                    LogUtil.d("MyTestService", "uncaughtException2: ")
                    Process.killProcess(Process.myPid())
                    System.exit(0)

                }

            }
        }

    }

    /**
     * 关掉强制跳回App
     */
    fun stopForceBackToApp(){
        forceBackToAppJob?.cancel()
        forceBackToAppJob = null
    }

    /**
     * 检测一个android程序是否在运行
     *
     * @param context
     * @param PackageName
     * @return
     */
    fun isServiceStarted(context: Context, packageName: String): Boolean {
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningProcesses = am.runningAppProcesses
        for (processInfo in runningProcesses) {
            if (processInfo.processName == packageName) {
                return true
            }
        }
        return false
    }

}