package com.base.filerecoveryrecyclebin.fragment

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.usage.StorageStatsManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.STORAGE_STATS_SERVICE
import android.content.Intent
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.os.storage.StorageManager
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.activity.MainActivity
import com.base.filerecoveryrecyclebin.activity.SettingActivity
import com.base.filerecoveryrecyclebin.activity.battery.BatteryInfoAnimationActivity
import com.base.filerecoveryrecyclebin.activity.junkclean.ScanJunk2Activity
import com.base.filerecoveryrecyclebin.activity.junkclean.ScanJunkActivity
import com.base.filerecoveryrecyclebin.activity.largefile.LargeFileAnimationActivity
import com.base.filerecoveryrecyclebin.activity.repeat.RepeatAnimationActivity
import com.base.filerecoveryrecyclebin.activity.screenshot.ScreenShotActivity
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
import com.base.filerecoveryrecyclebin.bean.ConstObject
import com.base.filerecoveryrecyclebin.databinding.FragmentHome3Binding
import com.base.filerecoveryrecyclebin.help.BaseFragment
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatSize
import com.base.filerecoveryrecyclebin.help.PermissionHelp.checkStorePermission
import com.base.filerecoveryrecyclebin.help.WeatherUtils
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.view.CleanGuideDialog
import com.base.filerecoveryrecyclebin.view.WeatherInterface
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.io.File
import kotlin.random.Random

class HomeFragment : BaseFragment<FragmentHome3Binding>() {
    private val TAG = "HomeFragment"

    override val binding: FragmentHome3Binding by lazy {
        FragmentHome3Binding.inflate(layoutInflater)
    }


    @SuppressLint("SetTextI18n")
    override fun setView() {
        binding.tvTitle.text = "Dumpster"
        val bean = WeatherUtils.getWeatherEntity()?.list?.get(0)
        bean?.let {
            var value = 22
            val min = bean.tempMin.toInt()
            val max = bean.tempMax.toInt()
            if (min == max) {
                value = max
            }
            if (min < max) {
                value = Random.nextInt(min, max)
            }
            val icon = when (WeatherUtils.getWeatherType(bean.iconDay.toInt())) {
                "Sunny day" -> R.mipmap.x_qing
                "Cloudy day" -> R.mipmap.x_yin
                "Rainy day" -> R.mipmap.x_dayu
                "Snowy day" -> R.mipmap.x_xiaxue
                "Greasy day" -> R.mipmap.x_wumaishachengbao
                "Unknown" -> R.mipmap.x_qing
                else -> R.mipmap.x_qing
            }
            binding.tvWendu.text = value.toString()
            binding.ivWeather.setImageResource(icon)
        }

        binding.lottie.repeatCount = ValueAnimator.INFINITE
        lifecycleScope.launch {
            (requireActivity() as MainActivity).photoSizeFlow.collectLatest { pair ->
                if (pair.second != 0L) {
                    binding.tvDuplicateSize.visibility = View.VISIBLE
                    binding.tvDuplicateSize.text = pair.second.toFormatSize()
                } else {
                    binding.tvDuplicateSize.visibility = View.GONE
                }
            }
        }
        showStorage()
        AdmobMaxHelper.admobMaxShowNativeAd(requireActivity(), binding.idFlNative)
        if (!ConstObject.hasCleaned) {
            //没有清理过就弹dialog引导
            CleanGuideDialog.Builder(requireContext()).build(this).show()
        }
    }

    var i = 0
    var lastClickTime = 0L
    override fun setListener() {
        binding.flScan.setOnClickListener {
            goClJk()
        }
        binding.tvClJk.setOnClickListener {
            goClJk()
        }
//        binding.idTvXz.setOnClickListener {
//            startActivity(Intent(context, XzLoadingActivity::class.java))
//        }
        binding.cardJunkClean.setOnClickListener {
            startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
        }
        binding.cardLargeFile.setOnClickListener {
            startActivity(Intent(requireContext(), LargeFileAnimationActivity::class.java))
        }
        binding.cardDuplicate.setOnClickListener {
            startActivity(Intent(requireContext(), RepeatAnimationActivity::class.java))
        }
        binding.cardBattery.setOnClickListener {
            startActivity(Intent(requireContext(), BatteryInfoAnimationActivity::class.java))
        }
        binding.cardScreenshot.setOnClickListener {
            startActivity(Intent(requireContext(), ScreenShotActivity::class.java))
        }

        binding.flSetting.setOnClickListener {
            startActivity(Intent(requireContext(), SettingActivity::class.java))
        }
        binding.llWeather.setOnClickListener {
            startActivity(Intent(requireContext(), WeatherInterface::class.java))
        }
        binding.ivArrowUp.setOnClickListener {
            val scrollDistance: Int = binding.nestedScrollView.getChildAt(0).height
            binding.nestedScrollView.smoothScrollTo(0, scrollDistance)
        }
        binding.tvTitle.setOnClickListener {
            if (System.currentTimeMillis() - lastClickTime > 5 * 1000 && i != 0) {
                lastClickTime = 0
                i = 0
            }
            if (i == 20) {
                copyUuidGid()
                i = 0
            }
            i++
            lastClickTime = System.currentTimeMillis()
        }

    }

    private fun goClJk(){
        val jumpJunkFirstAd =
            AppPreferences.getInstance().getString("isjunkPlayAd", "0").toInt()
        if (jumpJunkFirstAd == 1) {
            startActivity(Intent(requireContext(), ScanJunk2Activity::class.java))
        } else {
            startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
        }
    }

    private fun copyUuidGid() {
        val uuid = AppPreferences.getInstance().getString("uuid", "")
        val gid = AppPreferences.getInstance().getString("gid", "")
        // 获取系统服务ClipboardManager
        val clipboard: ClipboardManager =
            requireContext().getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个ClipData对象，其中包含要复制的文本
        val clip = ClipData.newPlainText("uuid", "uuid=$uuid gid=$gid")
        // 将ClipData对象设置到剪贴板中
        clipboard.setPrimaryClip(clip)
        Toast.makeText(requireContext(), "copy", Toast.LENGTH_SHORT).show()
    }


    override fun onPause() {
        super.onPause()
        binding.lottie.pauseAnimation()

    }

    @SuppressLint("SetTextI18n")
    override fun onResume() {
        super.onResume()
        binding.lottie.resumeAnimation()
        if (requireContext().checkStorePermission()) {

        }
    }

    @SuppressLint("SetTextI18n")
    fun showStorage() {
        binding.llStorage.visibility = View.VISIBLE

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val storageStatsManager =
                requireContext().getSystemService(STORAGE_STATS_SERVICE) as StorageStatsManager

            Thread {
                val totalBytes = storageStatsManager.getTotalBytes(StorageManager.UUID_DEFAULT)
                val usedBytes =
                    totalBytes - storageStatsManager.getFreeBytes(StorageManager.UUID_DEFAULT)
                binding.root.post {
                    binding.tvStorage.text =
                        "${usedBytes.toFormatSize()} / ${totalBytes.toFormatSize()}"
                }
            }.start()

        } else {
            val path1: File = Environment.getDataDirectory()
            val stat1 = StatFs(path1.path)
            val path2: File = Environment.getExternalStorageDirectory()
            val stat2 = StatFs(path2.path)
            val totalSize = (stat1.totalBytes + stat2.totalBytes).toFormatSize()
            val usedSize =
                ((stat1.totalBytes + stat2.totalBytes) - (stat1.availableBytes + stat2.availableBytes)).toFormatSize()
            binding.tvStorage.text = "$usedSize / $totalSize"
        }
    }

}