package com.base.pdfreader2.ui.main

import android.graphics.Color
import android.view.View
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.angcyo.tablayout.delegate2.ViewPager2Delegate
import com.base.pdfreader2.R
import com.base.pdfreader2.bean.ConstObject
import com.base.pdfreader2.bean.ConstObject.BOOKMARK_DATA_TYPE
import com.base.pdfreader2.bean.ConstObject.DOCUMENT_DATA_TYPE
import com.base.pdfreader2.bean.ConstObject.RECENT_DATA_TYPE
import com.base.pdfreader2.bean.DocumentBean
import com.base.pdfreader2.databinding.ActivityMainBinding
import com.base.pdfreader2.helper.BaseActivity
import com.base.pdfreader2.ui.view.DialogView.showSortDialog
import com.base.pdfreader2.utils.BarUtils
import com.base.pdfreader2.utils.LogEx
import com.base.pdfreader2.utils.PermissionUtils.checkStorePermission
import com.base.pdfreader2.utils.PermissionUtils.requestStoragePermission

const val UI_MODE_NORMAL = "ui_mode_normal"
const val UI_MODE_SELECT = "ui_mode_select"
const val UI_MODE_SEARCH = "ui_mode_search"

class MainActivity : BaseActivity<ActivityMainBinding>() {

    private val TAG = "MainActivity"

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

    private val pdfPage: DocumentFragment by lazy {
        DocumentFragment(DocumentBean.TYPE_PDF)
    }

    private val wordPage: DocumentFragment by lazy {
        DocumentFragment(DocumentBean.TYPE_WORD)
    }

    private val excelPage: DocumentFragment by lazy {
        DocumentFragment(DocumentBean.TYPE_EXCEL)
    }

    private val pptPage: DocumentFragment by lazy {
        DocumentFragment(DocumentBean.TYPE_PPT)
    }

    private val fragments by lazy {
        mutableListOf(pdfPage, wordPage, excelPage, pptPage)
    }
    var currentPage: DocumentFragment = pdfPage

    var dataType: String = DOCUMENT_DATA_TYPE

    private lateinit var pageAdapter: FragmentStateAdapter
    var uiMode = UI_MODE_NORMAL

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, !ConstObject.modeNight)
        if (ConstObject.modeNight) {
            BarUtils.setStatusBarColor(this, Color.BLACK)
        } else {
            BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        }
//        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
//        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

        if (!checkStorePermission()) {
            requestStoragePermission(launcher) {}
        }
        initViewPager2()
        initTabLayout()

        binding.llDocument.isSelected = true
    }

    //OnBackPressedCallback 并将 isEnabled 设置为 false 时，默认的返回键行为将被禁用。
    lateinit var callback: OnBackPressedCallback
    override fun initListener() {
        super.initListener()

        callback = object : OnBackPressedCallback(false) {
            override fun handleOnBackPressed() {
                LogEx.logDebug(TAG, "handleOnBackPressed")


                if (uiMode == UI_MODE_SELECT) {
                    changeSelectUI(false)
                }
                if (uiMode == UI_MODE_SEARCH) {
//                  changeSearchUI(false)
                }
            }
        }
        onBackPressedDispatcher.addCallback(callback)
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        binding.llDocument.setOnClickListener {
            dataType = DOCUMENT_DATA_TYPE
            changeDocumentUI()
            currentPage.refreshData()
        }
        binding.llRecent.setOnClickListener {
            dataType = RECENT_DATA_TYPE
            changeRecentUI()
            currentPage.refreshData()
        }
        binding.llBookmark.setOnClickListener {
            dataType = BOOKMARK_DATA_TYPE
            changeBookmarkUI()
            currentPage.refreshData()
        }
        binding.llTool.setOnClickListener {
            changeToolUI()
        }

        binding.ivPaixu.setOnClickListener {
            showSortDialog {
                currentPage.refreshData()
            }
        }
        binding.ivSelect.setOnClickListener {
            changeSelectUI(true)
        }

    }

    private fun changeSelectUI(show: Boolean) {
        if (show) {
            uiMode = UI_MODE_SELECT
            binding.viewPager2.isUserInputEnabled = false
            callback.isEnabled = true
            binding.ivPaixu.visibility = View.INVISIBLE
            binding.tvTittle.visibility = View.INVISIBLE
            binding.ivSearch.visibility = View.INVISIBLE
            binding.ivSelect.visibility = View.INVISIBLE

            binding.llDocument.visibility = View.INVISIBLE
            binding.llRecent.visibility = View.INVISIBLE
            binding.llBookmark.visibility = View.INVISIBLE
            binding.llTool.visibility = View.INVISIBLE

            binding.llDelete.visibility = View.VISIBLE
            binding.llShare.visibility = View.VISIBLE
            binding.flFanhui.visibility = View.VISIBLE

            currentPage.changeSelectUi(true)
        } else {
            binding.viewPager2.isUserInputEnabled = true
            callback.isEnabled = false
            binding.ivPaixu.visibility = View.VISIBLE
            binding.ivSearch.visibility = View.VISIBLE
            binding.tvTittle.visibility = View.VISIBLE
            binding.ivSelect.visibility = View.VISIBLE

            binding.llDocument.visibility = View.VISIBLE
            binding.llRecent.visibility = View.VISIBLE
            binding.llBookmark.visibility = View.VISIBLE
            binding.llTool.visibility = View.VISIBLE

            binding.llDelete.visibility = View.INVISIBLE
            binding.llShare.visibility = View.INVISIBLE
            binding.flFanhui.visibility = View.GONE

            currentPage.changeSelectUi(false)
        }
    }


    private fun disSelectBottomNav() {
        binding.llDocument.isSelected = false
        binding.llRecent.isSelected = false
        binding.llBookmark.isSelected = false
        binding.llTool.isSelected = false
    }

    private fun changeDocumentUI() {
        disSelectBottomNav()
        binding.llDocument.isSelected = true
        binding.flTool.visibility = View.INVISIBLE
        binding.clDocument.visibility = View.VISIBLE
    }

    private fun changeRecentUI() {
        disSelectBottomNav()
        binding.llRecent.isSelected = true
        binding.flTool.visibility = View.INVISIBLE
        binding.clDocument.visibility = View.VISIBLE
    }

    private fun changeBookmarkUI() {
        disSelectBottomNav()
        binding.llBookmark.isSelected = true
        binding.flTool.visibility = View.INVISIBLE
        binding.clDocument.visibility = View.VISIBLE
    }

    private fun changeToolUI() {
        disSelectBottomNav()
        binding.llTool.isSelected = true
        binding.clDocument.visibility = View.INVISIBLE
        binding.flTool.visibility = View.VISIBLE
    }


    private fun initViewPager2() {
        pageAdapter = object : FragmentStateAdapter(this) {
            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(this, R.color.color_de202a)
        val colorWord = ContextCompat.getColor(this, R.color.color_4f8df4)
        val colorExcel = ContextCompat.getColor(this, R.color.color_1ea362)
        val colorPpt = ContextCompat.getColor(this, R.color.color_f6b911)
        val deselectColor = ContextCompat.getColor(this, R.color.color_80ffffff)

        binding.tabLayoutDocument.apply {

            configTabLayoutConfig {
                tabSelectColor = Color.WHITE
                tabDeselectColor = deselectColor
                onSelectIndexChange = { fromIndex, selectIndexList, reselect, fromUser ->
                    val toIndex = selectIndexList.first()
                    binding.viewPager2.currentItem = toIndex
                    when (toIndex) {
                        0 -> {
                            binding.clTop.setBackgroundColor(colorPdf)
                        }

                        1 -> {
                            binding.clTop.setBackgroundColor(colorWord)
                        }

                        2 -> {
                            binding.clTop.setBackgroundColor(colorExcel)
                        }

                        3 -> {
                            binding.clTop.setBackgroundColor(colorPpt)
                        }
                    }
                    currentPage.refreshData()
                }
                dslSelector.updateStyle()
            }

        }
        ViewPager2Delegate.install(binding.viewPager2, binding.tabLayoutDocument)
    }


}