package com.hh.arome.services.keeplive

import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.os.Build
import androidx.annotation.RequiresApi
import com.hh.arome.activity.MainActivity
import com.hh.lib_base.Constants.LogcatValue
import com.hh.lib_base.log.AppLogUtils
import com.hh.lib_base.log.LogType



@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class MyJobService :JobService(){



    companion object{
        val TAG = "MyJobService"
        @Volatile
        var isWorking=false;
        fun startJob(context: Context) {
            isWorking = true
            val jobScheduler =
                context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
            //        setPersisted 在设备重启依然执行
            val builder = JobInfo.Builder(
                10, ComponentName(
                    context
                        .getPackageName(), MyJobService::class.java
                        .name
                )
            ).setPersisted(false)
            //小于7.0
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                // 每隔1s 执行一次 job
                builder.setPeriodic(1000)
            } else {
                //延迟执行任务
                //大于7.0的机型发现定时无效果，所需需要进行延时轮询
                builder.setMinimumLatency(1000)
            }
            jobScheduler.schedule(builder.build())
        }

        /**
         *
         * @author xwh
         * Time 2024/11/4
         * Description: 停止job任务
         *
        **/
        fun stopJob(context: Context) {
            isWorking = false
            val jobScheduler =
                context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
            jobScheduler.cancelAll()

        }
    }


    override fun onStopJob(params: JobParameters?): Boolean {

        return false
    }

    override fun onStartJob(params: JobParameters?): Boolean {

            try {
                val isLocalRun: Boolean = JobUtils.isRunningService(
                    this,
                    LocalService::class.java.name
                )
                val isRemoteRun: Boolean = JobUtils.isRunningService(
                    this,
                    RemoteService::class.java.name
                )

                val isActivityDestroyed: Boolean = JobUtils.isActivityDestroyed(
                    this,
                    MainActivity::class.java.name
                )

                //只有其中任何一个服务被干掉了，则进行start
                if (!isLocalRun || !isRemoteRun) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        // 8.0
                        startForegroundService(Intent(this, LocalService::class.java));
                        startForegroundService(Intent(this, RemoteService::class.java));
                    } else {
                        startService(Intent(this, LocalService::class.java))
                        startService(Intent(this, RemoteService::class.java))
                    }

                    try {
                        val logLine = Throwable().stackTrace[0].toString()
                        // 开始保存本地日志
                        AppLogUtils.saveLog(
                            LogType.Logcat, StringBuilder()
                                .append(LogcatValue.LINE)
                                .append(logLine).append(LogcatValue.WARP)
                                .append(LogcatValue.NODE)
                                .append("HHArome  服务重启")
                                .toString()
                        )
                    } catch (e: java.lang.Exception) {

                    }

                }

                if (isActivityDestroyed && isWorking) {
                    try {
                        val intent = Intent(this, MainActivity::class.java)
                        intent.setFlags(FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        startActivity(intent)

                        val logLine = Throwable().stackTrace[0].toString()
                        // 开始保存本地日志
                        AppLogUtils.saveLog(
                            LogType.Logcat, StringBuilder()
                                .append(LogcatValue.LINE)
                                .append(logLine).append(LogcatValue.WARP)
                                .append(LogcatValue.NODE)
                                .append("HHArome  MainActivity 重启")
                                .toString()
                        )
                    } catch (e: java.lang.Exception) {

                    }
                }


            } catch (e: java.lang.Exception) {

            } finally {
                //TODO 重复执行Job
                //如果7.0以上 轮训
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    startJob(this)
                }
            }
        return false
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_NOT_STICKY;
    }

}