package com.base.appzxhy.ui.main

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior.setTag
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.applovin.impl.sb
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.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

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)


    }

    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 -> {
                    (requireActivity() as MainActivity).jumpAction(it.key)
                }


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

            }

        }
//        Wave(/*Context context, */int offsetX, int offsetY, int velocity, float scaleX, float scaleY, int wave) {
//        super(context);
//            this.wave = wave;           //波幅（波宽）
//            this.scaleX = scaleX;       //水平拉伸量
//            this.scaleY = scaleY;       //竖直拉伸量
//            this.offsetX = offsetX;     //水平偏移量
//            this.offsetY = offsetY;     //竖直偏移量
//            this.velocity = velocity;   //移动速度（像素/秒）
//            this.path = new Path();
//        }

//        "70,25,1.4,1.4,-26\n" +
//                "100,5,1.4,1.2,15\n" +
//                "420,0,1.15,1,-10\n" +
//                "520,10,1.7,1.5,20\n" +
//                "220,0,1,1,-15"
        binding.WaveHeader1.setStartColor(R.color.colorPrimary)
        binding.WaveHeader1.setCloseColorId(R.color.colorPrimary)
        binding.WaveHeader1.setWaves("70,25,1.4,1.4,-26")
        binding.WaveHeader1.colorAlpha = 0.5f
        binding.WaveHeader1.visibility = View.GONE

        binding.WaveHeader2.setStartColor(R.color.color_aacbec)
        binding.WaveHeader2.setCloseColorId(R.color.color_aacbec)
        binding.WaveHeader2.setWaves("220,0,1,1,-15")
        binding.WaveHeader2.colorAlpha = 0.8f
        binding.WaveHeader2.visibility = View.GONE

        binding.WaveHeader3.colorAlpha = 1f
        binding.WaveHeader3.setWaves("25,5,1.15,1.2,25")
        binding.WaveHeader3.velocity=2f
        binding.WaveHeader3.visibility = View.VISIBLE
    }


    @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()
    }


}
