package com.base.appzxhy.ui.main

import android.annotation.SuppressLint
import android.app.ActivityManager
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.graphics.Insets
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.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.FragmentHome3Binding
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.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

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

    private val adapter = FeatureItemAdapter()

    private val featureList by lazy {

        listOf<FeatureBean>(
            FeatureBean(
                JUNK_CLEAN,
                R.string.clean_junk,
                R.drawable.icon_clean_h,
            ),
            FeatureBean(
                BATTERY_INFO,
                R.string.battery_info,
                R.drawable.icon_battery_h,
            ),
            FeatureBean(
                SIMILAR_PHOTOS,
                R.string.similar_photos,
                R.drawable.icon_similar_h,
            ),
            FeatureBean(
                UNINSTALL_APP,
                R.string.uninstall_app,
                R.drawable.icon_app_uninstall,
            ),

            FeatureBean(
                PHOTO_COMPRESSION,
                R.string.photo_compression,
                R.drawable.icon_compression_h,
            ).apply {
                span = 2
            },
            FeatureBean(
                SCREENSHOT_CLEAN,
                R.string.screenshot_clean,
                R.drawable.icon_screenshot_h,
            ).apply {
                span = 2
            },
            FeatureBean(
                LARGE_FILE_CLEAN,
                R.string.large_file_clean,
                R.drawable.icon_file_h,
            ).apply {
                span = 2
            },
        )
    }


    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
        }

        val layoutManager = GridLayoutManager(requireContext(), 2)
        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)

        binding.lottie.setMinFrame(0)
        binding.lottie.setMaxFrame(55)
        binding.lottie.speed = 0.75f
        binding.lottie.setRepeatCount(LottieDrawable.INFINITE) // 设置无限循环播放
        binding.lottie.setRepeatMode(LottieDrawable.REVERSE) // 设置每次播放结束后重新开始
        binding.lottie.playAnimation() // 开始播放动画
    }

    override fun initListener() {
        super.initListener()


        binding.flClean.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 -> {
                    (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.tvUsed.text = usedStorageSize.toFormatSize(1)
                binding.tvTotal.text = "/" + usedStorageSize.toFormatSize(1)
                binding.circleProgress.setProgressWithAnimation(percent.toFloat(), duration = 1000L, startDelay = 200L)
            }
        }
    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()

        initData()
    }


}
