package com.test.basd.onecleanmaster.display

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_MUTABLE
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.test.basd.onecleanmaster.R
import com.test.basd.onecleanmaster.activity.splash.NewSplashActivity
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_APP_MANAGER
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_BATTERY_OPTIMIZATION
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_BATTERY_PUSH
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_CHARGE
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_CLEAN_NOTIFICATION
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_CLEAN_SPEAKER
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_INSTALL_PACKAGE_PUSH
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_JUNK_CLEAN_PUSH
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_LARGE_FILE_PUSH
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_LOW_BATTERY_PUSH
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_NETWORK_TRAFFIC
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_PHONE_ACCELERATE
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_PHOTO_COMPRESS
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_RECENT_USE_APP
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_SIMILAR_IMAGE
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_UNINSTALL_PACKAGE_PUSH
import com.test.basd.onecleanmaster.bean.ConfigBean.Companion.ID_VIRUS_PUSH
import com.test.basd.onecleanmaster.helps.BaseApplication
import com.test.basd.onecleanmaster.helps.ComUtils
import com.test.basd.onecleanmaster.helps.EventHelper

import kotlin.random.Random


/**
 * 推送的帮助类，定义了推送逻辑
 * 动态申请 <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
 */
object NotificationHelper {

    private const val CHANNEL_ID = "sdad"
    private const val CHANNEL_NAME = "Quick Master"
    private val TAG = "NotificationHelper"
    val notificationId = 20086


    /**
     * 当前APP支持的通知类型
     */
    val supportNotification = arrayListOf(
        ID_JUNK_CLEAN_PUSH,
        ID_VIRUS_PUSH,
        ID_LARGE_FILE_PUSH,
        ID_BATTERY_PUSH,
        ID_CLEAN_NOTIFICATION,
        ID_PHOTO_COMPRESS,
        ID_APP_MANAGER,
        ID_NETWORK_TRAFFIC,
        ID_CLEAN_NOTIFICATION,
        ID_RECENT_USE_APP,
        ID_SIMILAR_IMAGE,
        ID_CLEAN_SPEAKER,
        ID_BATTERY_OPTIMIZATION,
        ID_PHONE_ACCELERATE,//被动推送加入主动推送列表
    )

    /**
     * 过滤可推送actionId
     */
    fun filterAction(pushCircleOrder: List<Int>): ArrayList<Int> {
        //过滤已有功能
        val filterList = arrayListOf<Int>()
        pushCircleOrder.forEach { action ->
            if (supportNotification.contains(action)) {
                filterList.add(action)
            }
        }
        return filterList
    }

    /**
     * 获取当前的推送id
     */
    fun getPresentPushId(): Int {
        val pushCircleOrder = ComUtils.getSpConfigBean().push_circle_order
        Log.d(TAG, "push_circle_order=$pushCircleOrder")
        val tempList = arrayListOf<Int>()

        val json = SPUtils.getInstance().getString("push_circle_order", "")
        if ((json == "") or (json == "null")) {//初始化
            val filterList = filterAction(pushCircleOrder)
            val initJson = Gson().toJson(filterList)
            SPUtils.getInstance().getString("push_circle_order", initJson)
            tempList.addAll(filterList)
        } else {
            val array = Gson().fromJson(json, object : TypeToken<Array<Int>>() {})
            tempList.addAll(array)

            if (tempList.isEmpty()) {
                val filterList = filterAction(pushCircleOrder)
                val saveJson = Gson().toJson(filterList)
                SPUtils.getInstance().put("push_circle_order", saveJson)
                tempList.addAll(filterList)
            }
        }

        val i = tempList[0]
        tempList.remove(i)

        val usedJson = Gson().toJson(tempList)
        SPUtils.getInstance().put("push_circle_order", usedJson)
        return i
    }

    /**
     * 发送通知对于
     * @param extra 额外参数
     */
    @SuppressLint("RemoteViewLayout")
    fun Context.postActionNotification(actionId: Int, extra: Int? = null, pushStayTime: Long? = null) {
        val remoteViews = RemoteViews(packageName, R.layout.notification_common_notify)
        when (actionId) {
            ID_JUNK_CLEAN_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_cleanjunk)
                remoteViews.setTextViewText(R.id.tv_desc, "Clean up remaining junk files")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

            ID_VIRUS_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_cleanjunk)
                remoteViews.setTextViewText(R.id.tv_desc, "Protect your device and privacy, scan for virus threats now!")
                remoteViews.setTextViewText(R.id.tv_btn, "Scan")
            }

            ID_BATTERY_OPTIMIZATION -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_batteryinfo)
                val random = Random.nextInt(0, 50)
                remoteViews.setTextViewText(R.id.tv_desc, "$random Apps are consuming photo power")
                remoteViews.setTextViewText(R.id.tv_btn, "Optimize")
            }

            ID_LARGE_FILE_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_large)
                remoteViews.setTextViewText(R.id.tv_desc, "Clean big files to free up storage space")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

            ID_PHOTO_COMPRESS -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_photo)
                remoteViews.setTextViewText(R.id.tv_desc, "Compress images to release more space")
                remoteViews.setTextViewText(R.id.tv_btn, "Compress")
            }

            ID_APP_MANAGER -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_appmanager)
                remoteViews.setTextViewText(R.id.tv_desc, "Check apps size and uninstall junk apps to release storage space")
                remoteViews.setTextViewText(R.id.tv_btn, "Manage")
            }

            ID_NETWORK_TRAFFIC -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_network)
                remoteViews.setTextViewText(R.id.tv_desc, "View network traffic usage and stop traffic-consuming apps.")
                remoteViews.setTextViewText(R.id.tv_btn, "View")
            }

            ID_CLEAN_NOTIFICATION -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_notification)
                remoteViews.setTextViewText(R.id.tv_desc, "Too many annoying notifications? Block and clean")
                remoteViews.setTextViewText(R.id.tv_btn, "View")
            }

            ID_RECENT_USE_APP -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_recent)
                remoteViews.setTextViewText(R.id.tv_desc, "Check and manage recently active apps")
                remoteViews.setTextViewText(R.id.tv_btn, "Manage")
            }

            ID_SIMILAR_IMAGE -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_similar)
                remoteViews.setTextViewText(R.id.tv_desc, "Check similar photos to release more space")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

            ID_CLEAN_SPEAKER -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_speaker)
                remoteViews.setTextViewText(R.id.tv_desc, "Clean the speaker dust and fix the low volume problem")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

//==================================下面是被动推送的情况===============================================

            ID_INSTALL_PACKAGE_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_recent)
                remoteViews.setTextViewText(R.id.tv_desc, "Install successfully, scan for virus threats now!")
                remoteViews.setTextViewText(R.id.tv_btn, "Scan")
            }

            ID_UNINSTALL_PACKAGE_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_recent)
                remoteViews.setTextViewText(R.id.tv_desc, "Uninstalled successfully, clean residual files from your device")
                remoteViews.setTextViewText(R.id.tv_btn, "Clean up")
            }

            ID_CHARGE -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_recent)
                remoteViews.setTextViewText(R.id.tv_desc, "View phone battery consumption recently")
                remoteViews.setTextViewText(R.id.tv_btn, "View")
            }

            ID_LOW_BATTERY_PUSH -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_recent)
                remoteViews.setTextViewText(R.id.tv_desc, "The battery is $extra%, view the battery information")
                remoteViews.setTextViewText(R.id.tv_btn, "View")
            }

            ID_PHONE_ACCELERATE -> {
                remoteViews.setImageViewResource(R.id.iv_icon, R.drawable.home_recent)
                remoteViews.setTextViewText(R.id.tv_desc, "Ram usage  reached $extra%, optimize now!")
                remoteViews.setTextViewText(R.id.tv_btn, "Optimize")
            }

            else -> {
                return
            }
        }

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) FLAG_MUTABLE else FLAG_UPDATE_CURRENT


        //cancel事件
        val cancelIntent = Intent(this, CloseNotificationReceiver::class.java).apply {
            action = CloseNotificationReceiver.action
            putExtra("notificationId", notificationId)
        }
        val cancelRequestCode = Random.nextInt(0, 1000)
        val cancelPendingIntent = PendingIntent.getBroadcast(BaseApplication.context, cancelRequestCode, cancelIntent, flag)
        remoteViews.setOnClickPendingIntent(R.id.fl_cancel, cancelPendingIntent)

        val intent = Intent(applicationContext, NewSplashActivity::class.java)
        val title: String = ""
        val desc: String = ""
        intent.putExtra("title", title)
        intent.putExtra("desc", desc)
        val customKey = "type"
        intent.putExtra(customKey, actionId)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        val bundle = Bundle()
        bundle.putInt(customKey, actionId)
        intent.putExtras(bundle)
        val uri =
            Uri.parse("cleanapp://com.test.basd.cleanmaster/com.test.basd.quickclean.activity.splash.NewSplashActivity?type=$actionId")
        intent.data = uri
//        intent.data = Uri.parse("myapp://splash?type=$actionId")
        //按钮事件
        val btnRequestCode = Random.nextInt(0, 1000)
        val btnPendingIntent = PendingIntent.getActivity(BaseApplication.context, btnRequestCode, intent, flag)
        remoteViews.setOnClickPendingIntent(R.id.fl_btn, btnPendingIntent)

        //每种类型保存值
        SPUtils.getInstance().put(actionId.toString(), System.currentTimeMillis())
        //大间隔所需值
        SPUtils.getInstance().put("all_last_push_time", System.currentTimeMillis())
        EventHelper.event(
            "pushCircleOrder_showNotification",
            "actionId=$actionId"
        )
        val requestCode = Random.nextInt(0, 1000)

        val pendingIntent = PendingIntent.getActivity(applicationContext, requestCode, intent, FLAG_UPDATE_CURRENT or FLAG_MUTABLE)
        NotificationUtils.showNotification(applicationContext, notificationId, remoteViews, R.id.fl_cancel, pendingIntent, pushStayTime ?: 0)

    }

    //创建通知通道
    private fun createNotificationChannel(
        context: Context,
        channelId: String = CHANNEL_ID,
        channelName: String = CHANNEL_NAME,
    ) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(channelId, channelName, importance).apply {
                enableLights(true)
                enableVibration(false)
                vibrationPattern = longArrayOf(0)
                lightColor = Color.RED
            }
            // Register the channel with the system
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    @SuppressLint("MissingPermission")
    //Manifest.permission.POST_NOTIFICATIONS
    fun showNotification(context: Context, intent: Intent, remoteViews: RemoteViews) {

        createNotificationChannel(context)

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.FLAG_MUTABLE
        } else {
            FLAG_UPDATE_CURRENT
        }

        //requestCode每次需要改变
        val requestCode = Random.nextInt(0, 1000)
        val pendingIntent = PendingIntent.getActivity(
            context, requestCode, intent, flag
        )
        val title = intent.getStringExtra("title")
        val desc = intent.getStringExtra("desc")


        val builder = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.mipmap.logo_small)
            .setCustomContentView(remoteViews)
            .setCustomBigContentView(remoteViews)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setColor(Color.TRANSPARENT)
            .setContentTitle(title)
            .setContentText(desc)
            .setAutoCancel(true)
            .setOngoing(true)
            .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
            .setVibrate(longArrayOf(0))
            .setContentIntent(pendingIntent)

        val notification: Notification = builder.build()
        val notificationManager = context.getSystemService(Service.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(notificationId, notification)
    }
}
