package com.tgv.malware.ui.main


import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import com.tgv.malware.R
import com.tgv.malware.base.BaseFragment
import com.tgv.malware.base.jumpAction
import com.tgv.malware.bean.FeatureBean
import com.tgv.malware.bean.FeatureBean.Companion.ANTIVIRUS
import com.tgv.malware.bean.FeatureBean.Companion.BATTERY_INFO
import com.tgv.malware.bean.FeatureBean.Companion.JUNK_CLEAN
import com.tgv.malware.bean.FeatureBean.Companion.LARGE_FILE_CLEAN
import com.tgv.malware.bean.FeatureBean.Companion.PHOTO_COMPRESSION
import com.tgv.malware.bean.FeatureBean.Companion.SCREENSHOT_CLEAN
import com.tgv.malware.bean.FeatureBean.Companion.SETTINGS
import com.tgv.malware.bean.FeatureBean.Companion.SIMILAR_PHOTOS
import com.tgv.malware.bean.FeatureBean.Companion.getFunctionTodayUsed
import com.tgv.malware.databinding.FragmentHomeBinding
import com.tgv.malware.ui.dialog.permissionStorageJump
import com.tgv.malware.ui.malware.MalwareDialog
import com.tgv.malware.ui.set.SettingActivity
import com.tgv.malware.utils.MyAnimationUtils
import com.tgv.malware.utils.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch


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

    private val adapter = FeatureItemAdapter()

    private val featureList by lazy {

        listOf<FeatureBean>(
            FeatureBean(
                JUNK_CLEAN,
                R.string.clean_junk,
                R.drawable.icon_clean,
                R.string.make_your_phone_clean,
                "#FFF7F2".toColorInt()
            ),
            FeatureBean(
                ANTIVIRUS,
                R.string.antivirus,
                R.drawable.icon_antivirus,
                R.string.mobile_antivirus_protection,
                "#F2FFF7".toColorInt()
            ),
            FeatureBean(
                SCREENSHOT_CLEAN,
                R.string.screenshot_clean,
                R.drawable.icon_screenshot,
                R.string.clear_phone_screenshot,
                "#FFFCF2".toColorInt()
            ),
            FeatureBean(
                LARGE_FILE_CLEAN,
                R.string.large_file_clean,
                R.drawable.icon_large_file_clean,
                R.string.clear_large_files_on_the_phone,
                "#F2FFF7".toColorInt()
            ),
            FeatureBean(
                SIMILAR_PHOTOS,
                R.string.similar_photos,
                R.drawable.icon_similar,
                R.string.clear_similar_pictures_on_the_phone,
                "#FBF7FF".toColorInt()
            ),
            FeatureBean(
                PHOTO_COMPRESSION,
                R.string.image_compression,
                R.drawable.icon_compression,
                R.string.compress_mobile_phone_images,
                "#FFF7F2".toColorInt()
            ),
            FeatureBean(
                BATTERY_INFO,
                R.string.battery_info,
                R.drawable.icon_battery,
                R.string.view_battery_information,
                "#F2FFF7".toColorInt()
            ),
            FeatureBean(
                SETTINGS,
                R.string.settings,
                R.drawable.icon_set,
                R.string.show_all_settings,
                "#FBF7FF".toColorInt()
            ),
        )
    }

    override fun initView() {
        super.initView()
        (requireActivity() as MainActivity).insetsCallBack = { insets ->
            binding.flTop.setPadding(0, insets.top, 0, 0)
        }
        binding.rv.adapter = adapter
        startAnimation()

    }

    override fun initListener() {
        super.initListener()

        binding.tvClean.setOnClickListener {
            (requireActivity() as MainActivity).permissionStorageJump(JUNK_CLEAN)
        }
        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 -> {
                    (requireActivity() as MainActivity).jumpAction(it.key)
                }


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

                ANTIVIRUS -> {
                    val dialog = MalwareDialog(requireActivity())
                    dialog.action = {
                        if (it) {
                            (requireActivity() as MainActivity).permissionStorageJump(ANTIVIRUS)
                        }
                    }
                    dialog.showDialog()

                }

            }
        }
        binding.ivUp.setOnClickListener {
            val lastChild = binding.nestedScrollView.getChildAt(binding.nestedScrollView.childCount - 1)
            binding.nestedScrollView.smoothScrollTo(0, lastChild.bottom)
        }
    }

    private fun startAnimation() {

        MyAnimationUtils.rotation(binding.ivYuan, 2000)

        binding.tvJunkFile.alpha = 0f
        ValueAnimator.ofFloat(0f, 1f).apply {
            this.duration = 1000
            this.startDelay = 1200
            addUpdateListener { animation ->
                val value = animation.animatedValue as Float
                binding.tvJunkFile.alpha = value
            }
            start()
        }

        val top = requireActivity().resources.getDimension(R.dimen.dp_6)
        ObjectAnimator.ofFloat(
            binding.ivUp,
            View.TRANSLATION_Y,
            0f,
            top
        ).apply {
            duration = 1000
            interpolator = LinearInterpolator()
            repeatCount = ObjectAnimator.INFINITE
            repeatMode = ValueAnimator.REVERSE
            start()
        }

    }

    @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.progressBarMemory.setProgress(100 - percentM, true)

                binding.tvStoragePercent.text = "$percent%"
                binding.progressBarStorage.setProgress(100 - percent, true)
            }
        }
    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        changeListTodayUsed()
        initData()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun changeListTodayUsed() {
        featureList[0].todayUsed = getFunctionTodayUsed(JUNK_CLEAN)
        featureList[1].todayUsed = getFunctionTodayUsed(ANTIVIRUS)
        adapter.submitList(featureList)
    }
}
