package com.base.pdfreader2.ui.main

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.inputmethod.EditorInfo
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.pdf.PdfActivity
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

    lateinit var searchAdapter: DocumentAdapter

    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()
        initSearchUI()
        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.flFanhui2.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)
        }
        binding.ivSearch.setOnClickListener {
            changeSearchUI(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 {
            uiMode = UI_MODE_NORMAL
            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 initSearchUI() {
        binding.editSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                LogEx.logDebug(TAG, "IME_ACTION_DONE")
                searchDocument()
            }
            false
        }
        binding.ivSearch2.setOnClickListener {
            searchDocument()
        }
        searchAdapter = DocumentAdapter()
        binding.rvSearch.adapter = searchAdapter
        searchAdapter.moreAction = { item ->
            currentPage.documentMoreAction.invoke(item)
        }
        searchAdapter.itemClick = {
            jumpDocument(it)
        }
    }

    private fun searchDocument() {
        if (binding.editSearch.text.isNotEmpty()) {
            val search = binding.editSearch.text.toString()
            val items = currentPage.getSearchItems(search.trim())
            val arrayList = arrayListOf<DocumentBean>()
            arrayList.addAll(items)
            if (arrayList.isNotEmpty()) {
                arrayList.map { it.uiType = 4 }
                searchAdapter.submitList(arrayList)
                binding.llEmpty.visibility = View.INVISIBLE
            } else {
                binding.llEmpty.visibility = View.VISIBLE
            }
        }
    }


    fun changeSearchUI(show: Boolean) {
        binding.llSearch.setOnClickListener { }
        if (show) {
            uiMode = UI_MODE_SEARCH
            callback.isEnabled = true
            binding.llSearch.visibility = View.VISIBLE
        } else {
            uiMode = UI_MODE_NORMAL
            callback.isEnabled = false
            binding.llSearch.visibility = View.GONE
            searchAdapter.submitList(listOf())
            binding.editSearch.setText("")
        }
    }

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

    private fun changeDocumentUI() {
        disSelectBottomNav()
        binding.tvTittle.text = resources.getString(R.string.document)
        binding.llDocument.isSelected = true
        binding.flTool.visibility = View.INVISIBLE
        binding.clDocument.visibility = View.VISIBLE
    }

    private fun changeRecentUI() {
        disSelectBottomNav()
        binding.tvTittle.text = resources.getString(R.string.recent)
        binding.llRecent.isSelected = true
        binding.flTool.visibility = View.INVISIBLE
        binding.clDocument.visibility = View.VISIBLE
    }

    private fun changeBookmarkUI() {
        disSelectBottomNav()
        binding.tvTittle.text = resources.getString(R.string.bookmark)
        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)
    }

    companion object {
        fun Activity.jumpDocument(item: DocumentBean) {
            if (item.type == DocumentBean.TYPE_PDF) {
                if (item.state == 0) {
                    startActivity(Intent(this, PdfActivity::class.java).apply {
                        putExtra("path", item.path)
                    })
                }
                if (item.state == 1) {
//                    showPdfPwdDialog(
//                        state = item.state,
//                        path = item.path,
//                        isCheckPwd = true,
//                        verificationAction = { pwd ->
//                            startActivity(Intent(this, PdfActivity::class.java).apply {
//                                putExtra("path", item.path)
//                                putExtra("pwd", pwd)
//                            })
//                        })
                }
            }
            if (item.type == DocumentBean.TYPE_WORD) {
//                WordActivity.wordDocumentBean = item
//                WordActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
            if (item.type == DocumentBean.TYPE_EXCEL) {
//                ExcelActivity.excelDocumentBean = item
//                ExcelActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
            if (item.type == DocumentBean.TYPE_PPT) {
//                PptActivity.pptDocumentBean = item
//                PptActivity.launchDocViewer(this, 3, item.path, -1, 100)
            }
        }
    }

}