package com.base.pdfviewerscannerwhite.ui.main

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.angcyo.tablayout.DslTabIndicator
import com.angcyo.tablayout.delegate2.ViewPager2Delegate
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.ConstObject.BOOKMARK_DATA_TYPE
import com.base.pdfviewerscannerwhite.bean.ConstObject.DOCUMENT_DATA_TYPE
import com.base.pdfviewerscannerwhite.bean.ConstObject.RECENT_DATA_TYPE
import com.base.pdfviewerscannerwhite.bean.ConstObject.UI_MODE_NORMAL
import com.base.pdfviewerscannerwhite.bean.ConstObject.UI_MODE_SEARCH
import com.base.pdfviewerscannerwhite.bean.ConstObject.UI_MODE_SELECT
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.databinding.FragmentDocumentBinding
import com.base.pdfviewerscannerwhite.helper.BaseFragment
import com.base.pdfviewerscannerwhite.ui.main.MainActivity.Companion.jumpDocument
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showSortDialog
import com.base.pdfviewerscannerwhite.utils.KeyBoardUtils.hideKeyboard
import com.base.pdfviewerscannerwhite.utils.KeyBoardUtils.showKeyBoard
import com.base.pdfviewerscannerwhite.utils.LogEx

class DocumentFragment(
    val dataType: String = ""
) : BaseFragment<FragmentDocumentBinding>() {

    private val TAG = "DocumentFragment"

    private val pdfPage: DocumentPageFragment by lazy {
        DocumentPageFragment(DocumentBean.TYPE_PDF, dataType)
    }
    private val wordPage: DocumentPageFragment by lazy {
        DocumentPageFragment(DocumentBean.TYPE_WORD, dataType)
    }
    private val excelPage: DocumentPageFragment by lazy {
        DocumentPageFragment(DocumentBean.TYPE_EXCEL, dataType)
    }
    private val pptPage: DocumentPageFragment by lazy {
        DocumentPageFragment(DocumentBean.TYPE_PPT, dataType)
    }
    private val fragments by lazy {
        mutableListOf(pdfPage, wordPage, excelPage, pptPage)
    }
    var currentPage: DocumentPageFragment = pdfPage

    override val binding: FragmentDocumentBinding by lazy {
        FragmentDocumentBinding.inflate(layoutInflater)
    }
    lateinit var searchAdapter: DocumentAdapter

    var uiMode = UI_MODE_NORMAL

    private lateinit var pageAdapter: FragmentStateAdapter


    @SuppressLint("SetTextI18n")
    override fun setView() {
        when (dataType) {
            DOCUMENT_DATA_TYPE -> {
                binding.tvTittle.text = this.resources.getString(R.string.document)
            }

            RECENT_DATA_TYPE -> {
                binding.tvTittle.text = this.resources.getString(R.string.recent)
                binding.ivPaixu.visibility = View.INVISIBLE
            }

            BOOKMARK_DATA_TYPE -> {
                binding.tvTittle.text = this.resources.getString(R.string.bookmark)
            }

        }
        initPageViewer()
        initTabLayout()
        initSearchAdapter()
        isInitialized = true
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            return
        }
        currentPage.refreshData()
    }

    private fun initSearchAdapter() {
        searchAdapter = DocumentAdapter(requireActivity())
        binding.rvSearch.adapter = searchAdapter
        searchAdapter.moreAction = { item ->
            currentPage.documentMoreAction.invoke(item)
        }
        searchAdapter.itemClick = {
            requireActivity().jumpDocument(it)
        }

    }

    override fun setListener() {
        super.setListener()

        binding.flFanhui.setOnClickListener {
            (requireActivity() as MainActivity).onBackPressedDispatcher.onBackPressed()
        }
        binding.ivXuanze.setOnClickListener {
            changeSelectUI(true)
        }
        binding.ivSearch.setOnClickListener {
            changeSearchUI(true)
        }
        binding.ivAllSelector.setOnClickListener {
            binding.ivAllSelector.isSelected = !binding.ivAllSelector.isSelected
            changePageSelect(binding.ivAllSelector.isSelected)
        }
        binding.editSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                LogEx.logDebug(TAG, "IME_ACTION_DONE")
                searchDocument()
            }
            false
        }
        binding.ivPaixu.setOnClickListener {
            requireContext().showSortDialog {
                currentPage.refreshData()
            }
        }
    }

    private fun initPageViewer() {
        LogEx.logDebug(TAG, "initPageViewer dataType=$dataType")
        pageAdapter = object : FragmentStateAdapter(this@DocumentFragment) {
            override fun getItemCount(): Int {
                return fragments.size
            }

            override fun createFragment(position: Int): Fragment {
                return fragments[position]
            }
        }
        binding.viewPager2.run {
            isUserInputEnabled = true
            //https://www.jianshu.com/p/f69bd30cf5b0
            //FragmentStateAdapter 这里必须传人fragment
            adapter = pageAdapter
        }
        binding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
                if (position == 3 && positionOffset > 0) {
                    binding.viewPager2.setCurrentItem(position, false)
                }
            }

            override fun onPageSelected(position: Int) {
                currentPage = fragments[position]
            }
        })
    }

    private fun initTabLayout() {
        val colorPdf = ContextCompat.getColor(requireContext(), R.color.color_f02f2b)
        val colorWord = ContextCompat.getColor(requireContext(), R.color.color_0592ee)
        val colorExcel = ContextCompat.getColor(requireContext(), R.color.color_149b55)
        val colorPpt = ContextCompat.getColor(requireContext(), R.color.color_ffa127)
        binding.tabLayoutDocument.apply {
            tabIndicator.indicatorWidth =
                this.resources.getDimensionPixelOffset(R.dimen.dp_50)
            tabIndicator.indicatorHeight =
                this.resources.getDimensionPixelOffset(R.dimen.dp_4)
            tabIndicator.indicatorStyle =
                DslTabIndicator.INDICATOR_STYLE_BOTTOM

            configTabLayoutConfig {
                onSelectIndexChange = { fromIndex, selectIndexList, reselect, fromUser ->
                    val toIndex = selectIndexList.first()
                    when (toIndex) {
                        0 -> {
                            tabSelectColor = colorPdf
                            tabIndicator.indicatorColor = colorPdf
                            binding.viewPager2.currentItem = 0
                        }

                        1 -> {
                            tabSelectColor = colorWord
                            tabIndicator.indicatorColor = colorWord
                            binding.viewPager2.currentItem = 1
                        }

                        2 -> {
                            tabSelectColor = colorExcel
                            tabIndicator.indicatorColor = colorExcel
                            binding.viewPager2.currentItem = 2
                        }

                        3 -> {
                            tabSelectColor = colorPpt
                            tabIndicator.indicatorColor = colorPpt
                            binding.viewPager2.currentItem = 3
                        }
                    }
                    dslSelector.updateStyle()
                }
            }
        }
        ViewPager2Delegate.install(binding.viewPager2, binding.tabLayoutDocument)
    }

    fun changeSelectUI(show: Boolean) {
        if (show) {
            binding.viewPager2.isUserInputEnabled = false
            (requireActivity() as MainActivity).callback.isEnabled = true
            uiMode = UI_MODE_SELECT

            binding.ivPaixu.visibility = View.INVISIBLE
            binding.ivXuanze.visibility = View.INVISIBLE
            binding.ivSearch.visibility = View.INVISIBLE
            binding.tvTittle.visibility = View.INVISIBLE

            binding.flFanhui.visibility = View.VISIBLE
            binding.ivAllSelector.visibility = View.VISIBLE

            (requireActivity() as MainActivity).changeSelectUI(true)

            currentPage.changeSelectUi(true)
        } else {
            binding.viewPager2.isUserInputEnabled = true
            (requireActivity() as MainActivity).callback.isEnabled = false
            uiMode = UI_MODE_NORMAL
            binding.flFanhui.visibility = View.INVISIBLE
            binding.ivAllSelector.visibility = View.INVISIBLE

            if (dataType != RECENT_DATA_TYPE) {
                binding.ivPaixu.visibility = View.VISIBLE
            }
            binding.ivXuanze.visibility = View.VISIBLE
            binding.ivSearch.visibility = View.VISIBLE
            binding.tvTittle.visibility = View.VISIBLE


            (requireActivity() as MainActivity).changeSelectUI(false)
            currentPage.changeSelectUi(false)
        }

    }

    private fun changePageSelect(select: Boolean) {
        currentPage.changItemSelect(select)
    }


    @SuppressLint("SetTextI18n")
    fun changeSearchUI(show: Boolean) {
        if (show) {
            uiMode = UI_MODE_SEARCH
            (requireActivity() as MainActivity).callback.isEnabled = true

            binding.card.elevation = 0f
            binding.tvTittle.visibility = View.INVISIBLE
            binding.ivPaixu.visibility = View.INVISIBLE
            binding.ivXuanze.visibility = View.INVISIBLE
            binding.llMainContent.visibility = View.INVISIBLE
            binding.llEmpty.visibility = View.INVISIBLE
            binding.editSearch.setText("")

            binding.flFanhui.visibility = View.VISIBLE
            binding.editSearch.visibility = View.VISIBLE
            binding.flSearch.visibility = View.VISIBLE

            (requireActivity() as MainActivity).changeSearchUI(true)

            requireContext().showKeyBoard(binding.editSearch)

        } else {
            uiMode = UI_MODE_NORMAL
            (requireActivity() as MainActivity).callback.isEnabled = false

            binding.card.elevation = resources.getDimension(R.dimen.dp_5)
            binding.editSearch.visibility = View.INVISIBLE
            binding.flFanhui.visibility = View.INVISIBLE
            binding.flSearch.visibility = View.INVISIBLE

            binding.tvTittle.visibility = View.VISIBLE
            if (dataType != RECENT_DATA_TYPE) {
                binding.ivPaixu.visibility = View.VISIBLE
            }
            binding.ivXuanze.visibility = View.VISIBLE
            binding.llMainContent.visibility = View.VISIBLE

            (requireActivity() as MainActivity).changeSearchUI(false)

            requireContext().hideKeyboard(binding.editSearch)
            searchAdapter.submitList(listOf())
        }

    }


    private fun searchDocument() {
        if (binding.editSearch.text.isNotEmpty()) {
            val search = binding.editSearch.text.toString()
            val item = currentPage.getSearchItems(search)
            if (item.isNotEmpty()) {
                item.map { it.uiType = 4 }
                searchAdapter.submitList(item)
                binding.llEmpty.visibility = View.INVISIBLE
            } else {
                binding.llEmpty.visibility = View.VISIBLE
            }
        }
    }

    fun searchDeleteDocument(item: DocumentBean) {
        searchAdapter.remove(item)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        LogEx.logDebug(TAG, "onDestroyView")
        binding.viewPager2.removeAllViews()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        LogEx.logDebug(TAG, "onSaveInstanceState")
    }

}