package com.base.easyfilemanager.fragment

import android.content.Intent
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import com.base.easyfilemanager.activity.FileManagerActivity
import com.base.easyfilemanager.R
import com.base.easyfilemanager.activity.FileCategoryActivity
import com.base.easyfilemanager.activity.home.NewMainActivity
import com.base.easyfilemanager.adapter.FileCategoryAdapter
import com.base.easyfilemanager.bean.FileCategoryBean
import com.base.easyfilemanager.databinding.FragmentFileCategoryBinding
import com.base.easyfilemanager.helps.BaseFragment
import com.base.easyfilemanager.helps.KotlinExt.toFormatSize
import com.base.easyfilemanager.helps.PermissionHelp.checkStorePermission
import com.base.easyfilemanager.helps.PermissionHelp.requestStorePermission
import com.base.easyfilemanager.helps.ads.AdmobUtils
import com.base.easyfilemanager.utils.MediaStoreEx
import com.base.easyfilemanager.view.DialogViews.showGerPermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch


class FileCategoryFragment : BaseFragment<FragmentFileCategoryBinding>() {

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

    private lateinit var categoryAdapter: FileCategoryAdapter
    private lateinit var recentAdapter: FileCategoryAdapter

    private val categoryList = listOf(
        FileCategoryBean(FileCategoryBean.Audio, R.mipmap.audio, FileCategoryBean.Audio),
        FileCategoryBean(FileCategoryBean.Image, R.mipmap.image, FileCategoryBean.Image),
        FileCategoryBean(FileCategoryBean.Video, R.mipmap.video, FileCategoryBean.Video),
        FileCategoryBean(FileCategoryBean.ZIP, R.mipmap.zip, FileCategoryBean.ZIP),
        FileCategoryBean(FileCategoryBean.APK, R.mipmap.apk, FileCategoryBean.APK),
//        FileCategoryBean(FileCategoryBean.Empty, R.mipmap.empty, FileCategoryBean.Empty),
    )


    override fun setView() {

        categoryAdapter = FileCategoryAdapter(FileCategoryAdapter.MODE_CATEGORY, ::itemClick)
        val layoutManager = GridLayoutManager(requireContext(), 3)
        layoutManager.spanSizeLookup = object : SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                // 根据你的需求来决定每个item应该占据的列数
                // 例如，如果每个item都应该平分宽度，可以返回1
                return 1
            }
        }
        binding.rvCategory.layoutManager = layoutManager
        binding.rvCategory.adapter = categoryAdapter
        categoryAdapter.setData(categoryList)

        recentAdapter = FileCategoryAdapter(FileCategoryAdapter.MODE_RECENT, ::itemClick)
        binding.rvRecent.adapter = recentAdapter

        val total = totalSize().toFormatSize().split(" ")
        binding.tvTotal.text = total[0]
        binding.tvTotalUnit.text = total[1]

        val used = (totalSize() - availableSize()).toFormatSize().split(" ")
        binding.tvUsed.text = used[0]
        binding.tvUsedUnit.text = used[1]

        AdmobUtils.showNativeAd(requireActivity(), binding.flAd)
    }

    override fun setListener() {
        binding.tvAuthorization.setOnClickListener {
            requireContext().showGerPermission(deny = {}, allow = {
                val launcher = (requireActivity() as NewMainActivity).launcher
                requireContext().requestStorePermission(launcher, result = { flag ->
                    if (flag) {
                        binding.llPermission.visibility = View.GONE
                        binding.tvAuthorization.visibility = View.GONE
                        binding.rvRecent.visibility = View.VISIBLE
                        binding.llAll.isVisible = true
                        loadRecentImageVideo()
                    } else {
                        binding.llAll.isVisible = false
                    }
                })
            })
        }
        binding.llAll.isVisible = requireContext().checkStorePermission()
        binding.llAll.setOnClickListener {
            itemClick(FileCategoryBean.Image)
        }
        binding.flManager.setOnClickListener {
            if (requireContext().checkStorePermission()) {
                startActivity(Intent(requireContext(), FileManagerActivity::class.java))
            } else {
                requireContext().showGerPermission(
                    "Our application needs to manager your files Before you authorize, we need to confirm with you:",
                    deny = {},
                    allow = {
                        val launcher = (requireActivity() as NewMainActivity).launcher
                        requireContext().requestStorePermission(launcher, result = {
                            if (it) {
                                startActivity(Intent(requireContext(), FileManagerActivity::class.java))
                            }
                        })

                    }
                )
            }
        }

    }

    private fun itemClick(key: String) {
        requireContext().startActivity(Intent(requireContext(), FileCategoryActivity::class.java).apply {
            putExtra("type", key)
        })
    }


    private fun refreshRecent() {
        binding.llPermission.visibility = View.GONE
        binding.rvRecent.visibility = View.VISIBLE
        loadRecentImageVideo()
    }

    private fun loadRecentImageVideo() = lifecycleScope.launch(Dispatchers.Main) {
        val imageList = arrayListOf<FileCategoryBean>()
        async {
            val list =
                MediaStoreEx.recentImage(requireContext()).map { FileCategoryBean(key = FileCategoryBean.Image, url = it.toString()) }
            imageList.addAll(list)
        }.await()
        if (imageList.isEmpty()) {
            binding.llEmpty.visibility = View.VISIBLE
        } else {
            recentAdapter.setData(imageList)
        }
    }


    override fun onStart() {
        super.onStart()

    }

    override fun onPause() {
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
        if (requireContext().checkStorePermission()) {
            refreshRecent()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}