package com.base.pdfviewerscannerwhite.ui.main

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.ads.AdmobHelper
import com.base.pdfviewerscannerwhite.ads.AdmobHelper.lastOpenDocumentShowAd
import com.base.pdfviewerscannerwhite.ads.admob.AdmobInterstitialUtils
import com.base.pdfviewerscannerwhite.ads.admob.AdmobNativeUtils
import com.base.pdfviewerscannerwhite.bean.ConstObject
import com.base.pdfviewerscannerwhite.bean.ConstObject.UI_SORT_FINAL_MODIFIED
import com.base.pdfviewerscannerwhite.bean.ConstObject.UI_SORT_NAME_A_Z
import com.base.pdfviewerscannerwhite.bean.ConstObject.UI_SORT_NAME_Z_A
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.bean.DocumentBean.Companion.TYPE_EXCEL
import com.base.pdfviewerscannerwhite.bean.DocumentBean.Companion.TYPE_PDF
import com.base.pdfviewerscannerwhite.bean.DocumentBean.Companion.TYPE_PPT
import com.base.pdfviewerscannerwhite.bean.DocumentBean.Companion.TYPE_WORD
import com.base.pdfviewerscannerwhite.databinding.FragmentDocumentPageBinding
import com.base.pdfviewerscannerwhite.helper.BaseFragment
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfSelectActivity
import com.base.pdfviewerscannerwhite.ui.document.pdf.PdfSplitActivity
import com.base.pdfviewerscannerwhite.ui.main.MainActivity.Companion.jumpDocument
import com.base.pdfviewerscannerwhite.ui.view.DialogView.SortMode
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDocumentHomeMoreDialog
import com.base.pdfviewerscannerwhite.ui.view.PdfDialog.showPdfHomeMoreDialog
import com.base.pdfviewerscannerwhite.utils.LogEx
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.util.Locale

class DocumentPageFragment() : BaseFragment<FragmentDocumentPageBinding>(), DocumentView {

    private val TAG = "DocumentPageFragment"
    var type = TYPE_PDF
    var dataType: String = ""
    lateinit var adapter: DocumentAdapter
    lateinit var documentPresenter: DocumentPresenter

    constructor(type: String, dataType: String) : this() {
        this.type = type
        this.dataType = dataType
    }

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

    override fun setView() {
        documentPresenter = DocumentPresenter(requireContext(), this, type, lifecycleScope)
        initAdapter()
        isInitialized = true
    }

    override fun setListener() {
        super.setListener()
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.swipeRefreshLayout.isRefreshing = true
            binding.llEmpty.visibility = View.INVISIBLE
            binding.progressBar.visibility = View.VISIBLE
            binding.progressBar.isIndeterminate = true
            refreshData(false)
            lifecycleScope.launch(Dispatchers.Main) {
                delay(900)
                binding.swipeRefreshLayout.isRefreshing = false
                binding.progressBar.visibility = View.GONE
                binding.llEmpty.isVisible = isEmpty
            }
        }
    }


    override fun onResume() {
        super.onResume()
        refreshData()
    }


    var isEmpty: Boolean = false
    fun refreshData(showEmpty: Boolean = true) = lifecycleScope.launch(Dispatchers.IO) {
        isEmpty = false
        if (isInitialized && !isHidden && !MainPresenter.mainRefreshData) {
            LogEx.logDebug(TAG, "type=$type refreshData dataType=$dataType")
            val mainActivity = (requireActivity() as MainActivity?)
            val documentFragment = (parentFragment as DocumentFragment?)
            if (mainActivity == null || documentFragment == null) return@launch

            val list = mainActivity.mainPresenter.getDataByType(type, dataType)
            val dataType = documentFragment.dataType

            val arrayList = arrayListOf<DocumentBean>()

            if (dataType != ConstObject.RECENT_DATA_TYPE) {
                val sortList = sortByMode(list)
                arrayList.addAll(sortList)
            } else {
                arrayList.addAll(list)
            }

            launch(Dispatchers.Main) {
                if (showEmpty) {
                    binding.llEmpty.isVisible = arrayList.isEmpty()
                }

                val flag = AdmobHelper.isShowRvNativeAd()
                LogEx.logDebug(TAG, "isShowRvNativeAd flag=$flag")

                if (arrayList.isEmpty()) {
                    isEmpty = true
                    binding.flAd.visibility = View.VISIBLE
                    if (flag) {
                        AdmobNativeUtils.showNativeAd(requireActivity(), binding.flAd, R.layout.layout_admob_document)
                    }
                } else {
                    binding.flAd.visibility = View.GONE
                    if (flag) {
                        arrayList.add(1, DocumentBean().apply { isAd = true })
                    }
                }
                adapter.submitList(arrayList)
            }
//            Log.d("glc", "加载数据成功：" + type + "  list:" + list.size)
        } else {
//            Log.d("glc", "加载数据失败：" + type)
        }
    }

    private fun sortByMode(list: List<DocumentBean>): List<DocumentBean> {
        when (SortMode) {
            ConstObject.UI_SORT_LAST_MODIFIED -> {
                LogEx.logDebug(TAG, "sortByMode 1")
                return list.sortedByDescending { File(it.path).lastModified() }
            }

            UI_SORT_FINAL_MODIFIED -> {
                LogEx.logDebug(TAG, "sortByMode 2")
                return list.sortedBy { File(it.path).lastModified() }
            }

            UI_SORT_NAME_A_Z -> {
                LogEx.logDebug(TAG, "sortByMode 3")
                return list.sortedBy { File(it.path).name }
            }

            UI_SORT_NAME_Z_A -> {
                LogEx.logDebug(TAG, "sortByMode 4")
                return list.sortedByDescending { File(it.path).name }
            }

        }
        return list
    }


    private fun initAdapter() {
        adapter = DocumentAdapter(requireActivity())
        adapter.bookmarkAction = { addRemove, path ->
            documentPresenter.saveBookmarkChange(addRemove, path)
        }
        adapter.itemClick = { item ->
            if (AdmobHelper.isShowOpenDocumentInter()) {
                AdmobInterstitialUtils.showInterstitialAd(requireActivity()) {
                    if (it) {
                        lastOpenDocumentShowAd = System.currentTimeMillis()
                    }
                    requireActivity().jumpDocument(item)
                }
            } else {
                requireActivity().jumpDocument(item)
            }
        }
        adapter.moreAction = { item ->
            documentMoreAction.invoke(item)
        }
        binding.rv.adapter = adapter
    }

    var documentMoreAction: (item: DocumentBean) -> Unit = { item ->
        val mainActivity = (requireActivity() as MainActivity)
        val documentFragment = (parentFragment as DocumentFragment)
        if (item.type == TYPE_PDF) {
            requireContext().showPdfHomeMoreDialog(
                item, mainActivity, documentFragment, this
            )
        }

        if (item.type == TYPE_WORD || item.type == TYPE_EXCEL || item.type == TYPE_PPT) {
            requireContext().showDocumentHomeMoreDialog(item, mainActivity, documentFragment, this)
        }
    }


    override fun splitPdf(path: String, pwd: String?) {
        startActivity(Intent(requireContext(), PdfSplitActivity::class.java).apply {
            putExtra("path", path)
            putExtra("pwd", pwd)
        })
    }

    override fun mergePdf(path: String) {
        startActivity(Intent(requireContext(), PdfSelectActivity::class.java).apply {
            putExtra("doWhat", ConstObject.DO_MERGE_PDF)
        })
    }


    @SuppressLint("NotifyDataSetChanged")
    fun changeSelectUi(select: Boolean) {
        if (isVisible) {
            adapter.items.forEach {
                if (select) {
                    it.uiType = 1
                } else {
                    it.isSelect = false
                    it.uiType = 0
                }
            }
            adapter.notifyDataSetChanged()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun changItemSelect(select: Boolean) {
        adapter.items.forEach {
            it.isSelect = select
        }
        adapter.notifyDataSetChanged()
    }

    fun getSelectItems(): List<DocumentBean> {
        return adapter.items.filter { it.isSelect }
    }

    fun removeList(list: List<DocumentBean>) {
        list.forEach {
            adapter.remove(it)
        }
    }

    fun getSearchItems(search: String): List<DocumentBean> {
        if (isVisible) {
            return adapter.items.filter {
                File(it.path).name.lowercase(Locale.ENGLISH)
                    .contains(search.lowercase(Locale.ENGLISH))
            }
        }
        return listOf()
    }

}