package com.base.pdfviewerscannerwhite.ui.document.word

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.view.inputmethod.EditorInfo
import androidx.activity.addCallback
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.ads.AdmobHelper
import com.base.pdfviewerscannerwhite.ads.admob.AdmobInterstitialUtils
import com.base.pdfviewerscannerwhite.ads.admob.AdmobNativeUtils
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.databinding.ActivityWordBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.helper.MyApplication
import com.base.pdfviewerscannerwhite.ui.view.DialogView.showDocumentMore
import com.base.pdfviewerscannerwhite.utils.KeyBoardUtils.hideKeyboard
import com.base.pdfviewerscannerwhite.utils.KeyBoardUtils.showKeyBoard
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.SpStringUtils
import com.cherry.lib.doc.bean.DocEngine
import com.cherry.lib.doc.office.constant.EventConstant.APP_PAGE_DOWN_ID
import com.cherry.lib.doc.office.constant.EventConstant.APP_PAGE_UP_ID
import com.cherry.lib.doc.office.wp.control.WPControl
import com.cherry.lib.doc.office.wp.control.WPFind
import com.cherry.lib.doc.util.Constant
import java.io.File

class WordActivity : BaseActivity<ActivityWordBinding>() {

    private val TAG = "WordActivity"
    override val binding: ActivityWordBinding by lazy {
        ActivityWordBinding.inflate(layoutInflater)
    }

    private var totalPageNumber = 0
    private var currentPageNumber = 0
    override fun onResume() {
        super.onResume()
        updateAppLanguage(MyApplication.wordLanguage) {
            MyApplication.wordLanguage = it
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {

        initSpData(intent)

        val file = File(wordDocumentBean.path)
        binding.tvName.text = file.name

        binding.mDocView.getPageNumberAction = { current, total ->
            LogEx.logDebug(TAG, "getPageNumberAction")
            if (!binding.tvPageCount.isVisible) {
                binding.tvPageCount.isVisible = true
            }
            currentPageNumber = current
            totalPageNumber = total
            binding.tvPageCount.text = "$current/$total"
            setVerticalSeekbar(current, total)
        }
        binding.mDocView.singleTapAction = {
            LogEx.logDebug(TAG, "actionDownCallBack")
            if (isShowTopLayout) {
                LogEx.logDebug(TAG, "hide")
                hideTopLayout()
                hideBottomLayout()
            } else {
                showTopLayout()
                showBottomLayout()
                LogEx.logDebug(TAG, "show")
            }
        }
        AdmobNativeUtils.showNativeAd(this, binding.flAd, R.layout.layout_admob_document_in)
    }

    private fun setVerticalSeekbar(current: Int, max: Int) {
        binding.verticalSeekbar.showThumb = true
        binding.verticalSeekbar.thumbContainerColor = Color.TRANSPARENT
        binding.verticalSeekbar.thumbPlaceholderDrawable =
            ContextCompat.getDrawable(this, R.mipmap.fanye)
        if (binding.verticalSeekbar.maxValue != max - 1) {
            binding.verticalSeekbar.maxValue = max - 1
        }
        val process = max - current
        LogEx.logDebug(TAG, "process=$process $current $max")
        binding.verticalSeekbar.progress = process
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (isSearchUI) {
                cancelSearchUI()
                return@addCallback
            }
            LogEx.logDebug(TAG, "finishToMain")
            if (AdmobHelper.isShowCloseDocumentInter()) {
                AdmobInterstitialUtils.showInterstitialAd(this@WordActivity) {
                    if (it) {
                        AdmobHelper.lastCloseDocumentShowAd = System.currentTimeMillis()
                    }
                    binding.root.postDelayed({ finishToMain() }, 500)
                }
            } else {
                binding.root.postDelayed({ finishToMain() }, 500)
            }
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.ivXuanzhuan.setOnClickListener {
            switchOrientation()
        }
        binding.ivMore.setOnClickListener {
            showDocumentMore(wordDocumentBean, totalPageNumber - 1) { pageIndex ->
                val wpControl: WPControl? = (binding.mDocView.iOffice?.control?.appControl as WPControl?)
                if (pageIndex > currentPageNumber) {
                    wpControl?.wpView?.showPage(pageIndex, APP_PAGE_DOWN_ID)
                } else {
                    wpControl?.wpView?.showPage(pageIndex, APP_PAGE_UP_ID)
                }
//                wpControl.actionEvent(APP_PAGE_UP_ID, null)
            }
        }
        binding.ivSearch.setOnClickListener {
            showSearchUI()
        }
        binding.editSearch.addTextChangedListener {
            binding.mDocView.visibility = View.VISIBLE
            binding.tvPageCount.visibility = View.VISIBLE
            haveSearchResult = false
            hideBottomLayout()
            val wpControl: WPControl? = (binding.mDocView.iOffice?.control?.appControl as WPControl?)
            (wpControl?.find as WPFind?)?.resetSearchResult()
        }
        binding.editSearch.setOnEditorActionListener { v, actionId, event ->

            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // Perform your action here
                searchWord()
                return@setOnEditorActionListener true
            }
            false
        }
        binding.flPre.setOnClickListener {
            val wpControl: WPControl? = (binding.mDocView.iOffice?.control?.appControl as WPControl?)
            (wpControl?.find as WPFind?)?.findBackward()
        }
        binding.flNext.setOnClickListener {
            val wpControl: WPControl? = (binding.mDocView.iOffice?.control?.appControl as WPControl?)
            (wpControl?.find as WPFind).findForward()
        }

        binding.verticalSeekbar.setOnReleaseListener { progress ->
            val wpControl: WPControl? = (binding.mDocView.iOffice?.control?.appControl as WPControl?)
            LogEx.logDebug(TAG, "progress=$progress")
            val pageIndex = totalPageNumber - 1 - progress

            if (progress > currentPageNumber) {
                wpControl?.wpView?.showPage(pageIndex, APP_PAGE_DOWN_ID)
            } else {
                wpControl?.wpView?.showPage(pageIndex, APP_PAGE_UP_ID)
            }
        }
    }

    private var haveSearchResult: Boolean = false
    private fun searchWord() {
        val text = binding.editSearch.text
        if (text.isNullOrEmpty()) {
            return
        }
        val wpControl: WPControl? = (binding.mDocView.iOffice?.control?.appControl as WPControl?)
        val flag = (wpControl?.find as WPFind?)?.find(text.toString())
        haveSearchResult = flag ?: false
        if (flag == true) {
            hideKeyboard(binding.editSearch)
            showBottomLayout()
        } else {
            binding.mDocView.visibility = View.GONE
        }
    }


    private var isSearchUI: Boolean = false
    private fun showSearchUI() {
        isSearchUI = true
        binding.ivXuanzhuan.visibility = View.GONE
        binding.tvPageCount.visibility = View.GONE
        binding.ivMore.visibility = View.GONE
        binding.tvName.visibility = View.INVISIBLE
        binding.editSearch.visibility = View.VISIBLE
        showKeyBoard(binding.editSearch)
    }

    private fun cancelSearchUI() {
        hideBottomLayout()
        isSearchUI = false
        binding.editSearch.visibility = View.GONE
        binding.ivXuanzhuan.visibility = View.VISIBLE
        binding.ivMore.visibility = View.VISIBLE
        binding.tvName.visibility = View.VISIBLE
        binding.mDocView.visibility = View.VISIBLE
        binding.tvPageCount.visibility = View.VISIBLE
        hideKeyboard(binding.editSearch)
    }

    private fun switchOrientation() {
        requestedOrientation = if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        } else {
            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
    }


    private var isShowTopLayout = true
    private var isShowBottomLayout = false
    private fun showTopLayout() {
        if (!isShowTopLayout) {
            isShowTopLayout = true

            val topAnim: Animation = TranslateAnimation(0f, 0f, -binding.vAnimatorTop.height.toFloat(), 0f)
            topAnim.setDuration(200)
            topAnim.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation) {
                    binding.vAnimatorTop.visibility = View.VISIBLE
                }

                override fun onAnimationRepeat(animation: Animation) {}
                override fun onAnimationEnd(animation: Animation) {
                }
            })
            binding.vAnimatorTop.startAnimation(topAnim)
        }
    }

    private fun showBottomLayout() {

        if (isSearchUI && haveSearchResult) {
            val bottomAnim: Animation = TranslateAnimation(0f, 0f, binding.vAnimatorBottom.height.toFloat(), 0f)
            bottomAnim.duration = 200
            bottomAnim.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation) {
                    binding.vAnimatorBottom.visibility = View.VISIBLE
                }

                override fun onAnimationRepeat(animation: Animation) {}
                override fun onAnimationEnd(animation: Animation) {

                }
            })
            binding.vAnimatorBottom.startAnimation(bottomAnim)
        }
    }


    private fun hideTopLayout() {
        if (isShowTopLayout) {
            isShowTopLayout = false

            hideKeyboard(binding.editSearch)
            val topAnim: Animation = TranslateAnimation(0f, 0f, 0f, -binding.vAnimatorTop.height.toFloat())
            topAnim.setDuration(200)
            topAnim.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation) {}
                override fun onAnimationRepeat(animation: Animation) {}
                override fun onAnimationEnd(animation: Animation) {
                    binding.vAnimatorTop.visibility = View.GONE
                }
            })
            binding.vAnimatorTop.startAnimation(topAnim)


        }
    }

    private fun hideBottomLayout() {
        if (isSearchUI) {
            val bottomAnim: Animation = TranslateAnimation(0f, 0f, 0f, binding.vAnimatorBottom.height.toFloat())
            bottomAnim.duration = 200
            bottomAnim.setAnimationListener(object : Animation.AnimationListener {
                override fun onAnimationStart(animation: Animation) {}
                override fun onAnimationRepeat(animation: Animation) {}
                override fun onAnimationEnd(animation: Animation) {
                    binding.vAnimatorBottom.visibility = View.GONE
                }
            })
            binding.vAnimatorBottom.startAnimation(bottomAnim)
        }
    }


    private var docSourceType = 0
    private var fileType = -1
    private var engine: Int = DocEngine.INTERNAL.value
    private var pathOrUri: String? = null// 文件地址
    private fun initSpData(intent: Intent?) {
        pathOrUri = intent?.getStringExtra(Constant.INTENT_DATA_KEY)
        docSourceType = intent?.getIntExtra(Constant.INTENT_SOURCE_KEY, 0) ?: 0
        fileType = intent?.getIntExtra(Constant.INTENT_TYPE_KEY, -1) ?: -1
        engine = intent?.getIntExtra(Constant.INTENT_ENGINE_KEY, DocEngine.INTERNAL.value) ?: DocEngine.INTERNAL.value

        binding.mDocView.openDoc(this, pathOrUri, docSourceType, fileType, false)
        LogEx.logDebug(TAG, "initData-docUrl = $pathOrUri")
        LogEx.logDebug(TAG, "initData-docSourceType = $docSourceType")
        LogEx.logDebug(TAG, "initData-fileType = $fileType")
        LogEx.logDebug(TAG, "initData-engine = $engine")

        val value = (pathOrUri ?: "") + "_/_" + System.currentTimeMillis()
        LogEx.logDebug(TAG, "value=$value")
        SpStringUtils.addSpString(SpStringUtils.LAST_VIEW_KEY, value)
    }

    companion object {
        var wordDocumentBean: DocumentBean = DocumentBean()

        fun launchDocViewer(
            activity: Activity,
            docSourceType: Int,
            path: String?,
            fileType: Int? = null,
            engine: Int? = null
        ) {
            val intent = Intent(activity, WordActivity::class.java)
            intent.putExtra(Constant.INTENT_SOURCE_KEY, docSourceType)
            intent.putExtra(Constant.INTENT_DATA_KEY, path)
            intent.putExtra(Constant.INTENT_TYPE_KEY, fileType)
            intent.putExtra(Constant.INTENT_ENGINE_KEY, engine)
            activity.startActivity(intent)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.mDocView.onDestroy()
        AdmobNativeUtils.onDestroy()
    }

}