package com.base.appzxhy.ui.main

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.TooltipCompat
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.graphics.Insets
import androidx.core.graphics.toColorInt
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.airbnb.lottie.LottieDrawable
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseFragment
import com.base.appzxhy.base.jumpAction
import com.base.appzxhy.bean.FeatureBean
import com.base.appzxhy.bean.FeatureBean.Companion.BATTERY_INFO
import com.base.appzxhy.bean.FeatureBean.Companion.DEVICE_INFO
import com.base.appzxhy.bean.FeatureBean.Companion.JUNK_CLEAN
import com.base.appzxhy.bean.FeatureBean.Companion.LARGE_FILE_CLEAN
import com.base.appzxhy.bean.FeatureBean.Companion.PHOTO_COMPRESSION
import com.base.appzxhy.bean.FeatureBean.Companion.SCREENSHOT_CLEAN
import com.base.appzxhy.bean.FeatureBean.Companion.SETTINGS
import com.base.appzxhy.bean.FeatureBean.Companion.SIMILAR_PHOTOS
import com.base.appzxhy.bean.FeatureBean.Companion.UNINSTALL_APP
import com.base.appzxhy.databinding.FragmentHome1Binding
import com.base.appzxhy.ui.clean.JunkCleanActivity.Companion.getJunkSize
import com.base.appzxhy.ui.dialog.permissionStorageJump
import com.base.appzxhy.ui.set.SettingActivity
import com.base.appzxhy.utils.BarUtils
import com.base.appzxhy.utils.KotlinExt.toFormatSize
import com.base.appzxhy.utils.LogEx
import com.base.appzxhy.utils.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.random.Random


class HomeFragment : BaseFragment<FragmentHome1Binding>(FragmentHome1Binding::inflate) {

    private val adapter = FeatureItemAdapter()

    private val featureList by lazy {

        listOf<FeatureBean>(
            FeatureBean(
                JUNK_CLEAN,
                R.string.quick_clean,
                R.drawable.icon_clean_h,
            ).apply {
                color = R.color.color_fffaf7
            },
            FeatureBean(
                BATTERY_INFO,
                R.string.battery_info,
                R.drawable.icon_battery_h,
            ).apply {
                color = R.color.color_fdfff5
            },
            FeatureBean(
                PHOTO_COMPRESSION,
                R.string.photo_compression,
                R.drawable.icon_compression_h,
            ).apply {
                color = R.color.color_f5fff9
            },
            FeatureBean(
                SCREENSHOT_CLEAN,
                R.string.screenshot_clean,
                R.drawable.icon_screenshot_h,
            ).apply {
                color = R.color.color_f7feff
            },
            FeatureBean(
                SIMILAR_PHOTOS,
                R.string.similar_photos,
                R.drawable.icon_similar_h,
            ).apply {
                color = R.color.color_fefaff
            },
            FeatureBean(
                UNINSTALL_APP,
                R.string.uninstall_app,
                R.drawable.icon_app_uninstall_h,
            ).apply {
                color = R.color.color_fffafa
            },

            FeatureBean(
                DEVICE_INFO,
                R.string.device_info,
                R.drawable.icon_device_info_h,
            ).apply {
                color = R.color.color_fff7fe
            },
        )
    }


    override fun initView() {
        super.initView()
        binding.flTop.setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars: Insets = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            binding.flTop.setPadding(0, systemBars.top, 0, 0)
            insets
        }

        binding.lottie.setAnimation("home_cleaning_lottie.json")
        binding.lottie.enableMergePathsForKitKatAndAbove(true)
        binding.lottie.setRepeatCount(LottieDrawable.INFINITE)
        binding.lottie.playAnimation()

        val layoutManager = GridLayoutManager(requireContext(), 3)
        layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                val span = featureList[position].span
                return span
            }
        }
        binding.rv.layoutManager = layoutManager
        binding.rv.adapter = adapter
        adapter.submitList(featureList)


        initWave()
    }

    private fun initWave() {
        binding.wave1.setWaves(getRandomWave2())
        binding.wave1.progress = 0.15f
        binding.wave1.colorAlpha = 0.8f
        binding.wave1.startColor = "#AACBEC".toColorInt()
        binding.wave1.closeColor = "#AACBEC".toColorInt()
        binding.wave1.waveHeight = Random.nextInt(15, 30)
        binding.wave1.velocity = Random.nextInt(30, 60) * 0.1f
        binding.wave1.start()
        binding.wave1.visibility = View.VISIBLE

        binding.wave2.setWaves(getRandomWave1())
        binding.wave2.colorAlpha = 0.9f
        binding.wave2.progress = 0.15f
        binding.wave2.startColor = "#A9CAEB".toColorInt()
        binding.wave2.closeColor = "#A9CAEB".toColorInt()
        binding.wave2.waveHeight = Random.nextInt(15, 30)
        binding.wave2.velocity = Random.nextInt(30, 60) * 0.1f
        binding.wave2.start()
        binding.wave2.visibility = View.VISIBLE

        val randomWave = getRandomWave1()
        LogEx.logDebug(TAG, "randomWave=$randomWave")

        binding.wave3.setWaves(randomWave)
        binding.wave3.colorAlpha = 1f
        binding.wave3.progress = 0.13f
        binding.wave3.startColor = ContextCompat.getColor(requireContext(), R.color.colorPrimary)
        binding.wave3.closeColor = ContextCompat.getColor(requireContext(), R.color.colorPrimary)
        binding.wave3.waveHeight = Random.nextInt(15, 30)
        binding.wave3.velocity = Random.nextInt(30, 60) * 0.1f
        binding.wave3.start()
        binding.wave3.visibility = View.VISIBLE

        lifecycleScope.launch(Dispatchers.IO) {
            while (isActive) {
                delay(5000)
                launch(Dispatchers.Main) {
                    binding.wave1.velocity = Random.nextInt(80, 100) * 0.1f
                    binding.wave2.velocity = Random.nextInt(80, 100) * 0.1f
                    binding.wave3.velocity = Random.nextInt(80, 100) * 0.1f
                }
                delay(3000)
                launch(Dispatchers.Main) {
                    binding.wave1.velocity = Random.nextInt(30, 60) * 0.1f
                    binding.wave2.velocity = Random.nextInt(30, 60) * 0.1f
                    binding.wave3.velocity = Random.nextInt(30, 60) * 0.1f
                }
            }
        }
    }

    //    "70,25,1.4,1.4,-26\n"
    fun getRandomWave1(): String {
        val offsetX = Random.nextInt(70, 90)
        val offsetY = Random.nextInt(20, 30)
        val scaleX = Random.nextInt(10, 16) / 10f
        val scaleY = Random.nextInt(10, 15) / 10f
        val velocity = Random.nextInt(-30, -20)

        return "$offsetX,$offsetY,$scaleX,$scaleY,$velocity\n"
    }


    //  "100,5,1.4,1.2,15\n"
    fun getRandomWave2(): String {
        val offsetX = Random.nextInt(90, 120)
        val offsetY = Random.nextInt(3, 8)
        val scaleX = Random.nextInt(10, 16) / 10f
        val scaleY = Random.nextInt(9, 13) / 10f
        val velocity = Random.nextInt(8, 18)

        return "$offsetX,$offsetY,$scaleX,$scaleY,$velocity\n"
    }


    override fun initListener() {
        super.initListener()

        binding.flClean.setOnClickListener {
            (requireActivity() as MainActivity).permissionStorageJump(JUNK_CLEAN)
        }
        binding.tvClean.setOnClickListener {
            (requireActivity() as MainActivity).permissionStorageJump(JUNK_CLEAN)
        }



        adapter.itemClick = {


            when (it.key) {
                JUNK_CLEAN,
                SCREENSHOT_CLEAN,
                LARGE_FILE_CLEAN,
                PHOTO_COMPRESSION, SIMILAR_PHOTOS -> {
                    (requireActivity() as MainActivity).permissionStorageJump(it.key)
                }

                BATTERY_INFO, UNINSTALL_APP, DEVICE_INFO -> {
                    (requireActivity() as MainActivity).jumpAction(it.key)
                }


                SETTINGS -> {
                    (requireActivity() as MainActivity).goToAc(SettingActivity::class.java)
                }

            }

        }

    }


    @SuppressLint("SetTextI18n")
    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            val totalStorageSize = async { Utils.getTotalStorageSize() }.await()
            val availableStorageSize = async { Utils.getAvailableStorageSize() }.await()
            val usedStorageSize = totalStorageSize - availableStorageSize
            val totalStorage = Utils.getSizeFormat(totalStorageSize)
            val usedStorage = Utils.getSizeFormat(usedStorageSize)
            val percent = (usedStorageSize * 100 / totalStorageSize).toInt()

            val activityManager = getSystemService(requireContext(), ActivityManager::class.java) as ActivityManager
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager.getMemoryInfo(memoryInfo)
            val totalMem = memoryInfo.totalMem / (1024 * 1024) // 总内存（MB）
            val availMem = memoryInfo.availMem / (1024 * 1024) // 可用内存（MB）
            val isLowMemory = memoryInfo.lowMemory // 是否低内存状态
            val percentM = (100 * availMem / totalMem).toInt()

            launch(Dispatchers.Main) {
                binding.tvMemoryPercent.text = "$percentM%"
                binding.tvStoragePercent.text = "$percent%"
            }

            val size = getJunkSize(requireContext())
            launch(Dispatchers.Main) {
                if (size > 0) {
                    binding.tvSize.text = getString(R.string.junk_files, size.toFormatSize())
                } else {
                    binding.tvSize.visibility = View.INVISIBLE
                }
            }
        }
    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()

        initData()
    }


}
