package com.base.pdfreaderallpdfreader.ui.excel

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
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.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.ads.AdmobHelper
import com.base.pdfreaderallpdfreader.ads.admob.AdmobInterstitialUtils
import com.base.pdfreaderallpdfreader.ads.admob.AdmobNativeUtils
import com.base.pdfreaderallpdfreader.base.BaseActivity
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.databinding.ActivityExcelBinding
import com.base.pdfreaderallpdfreader.ui.view.DocumentDialog.showDocumentMore
import com.base.pdfreaderallpdfreader.utils.KeyBoardUtils.hideKeyboard
import com.base.pdfreaderallpdfreader.utils.KeyBoardUtils.showKeyBoard
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.SpStringUtils
import com.cherry.lib.doc.bean.DocEngine
import com.cherry.lib.doc.office.constant.EventConstant
import com.cherry.lib.doc.office.ss.control.SSControl
import com.cherry.lib.doc.office.ss.control.Spreadsheet
import com.cherry.lib.doc.office.ss.sheetbar.SheetBar
import com.cherry.lib.doc.util.Constant
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class ExcelActivity : BaseActivity<ActivityExcelBinding>() {

    private val TAG = "ExcelActivity"

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

    companion object {
        var excelDocumentBean: DocumentBean = DocumentBean()
        fun launchDocViewer(
            activity: Activity,
            docSourceType: Int,
            pathOrUri: String?,
            fileType: Int? = null,
            engine: Int? = null
        ) {
            val intent = Intent(activity, ExcelActivity::class.java)
            intent.putExtra(Constant.INTENT_SOURCE_KEY, docSourceType)
            intent.putExtra(Constant.INTENT_DATA_KEY, pathOrUri)
            intent.putExtra(Constant.INTENT_TYPE_KEY, fileType)
            intent.putExtra(Constant.INTENT_ENGINE_KEY, engine)
            activity.startActivity(intent)
        }
    }

    override fun initView() {
        initSpData(intent)
        val file = File(pathOrUri ?: "")
        if (file.exists()) {
            binding.tvName.text = file.name
        }
        AdmobNativeUtils.showNativeAd(this, binding.flAd, R.layout.layout_admob_document_in)
    }

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

    @SuppressLint("ClickableViewAccessibility")
    override fun initListener() {
        super.initListener()

        onBackPressedDispatcher.addCallback {
            if (isSearchUI) {
                cancelSearchUI()
                return@addCallback
            }
            if (AdmobHelper.isShowCloseDocumentInter()) {
                AdmobInterstitialUtils.showInterstitialAd(this@ExcelActivity) {
                    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(excelDocumentBean)
        }
        binding.mDocView.singleTapAction = {
            LogEx.logDebug(TAG, "actionDownCallBack")
            if (isShowTopLayout) {
                LogEx.logDebug(TAG, "hide")
                hideTopLayout()
                hideBottomLayout()
            } else {
                showTopLayout()
                showBottomLayout()
                LogEx.logDebug(TAG, "show")
            }
        }
        binding.ivSearch.setOnClickListener {
            showSearchUI()
        }
        binding.editSearch.addTextChangedListener {
            binding.mDocView.visibility = View.VISIBLE
            haveSearchResult = false
            hideBottomLayout()
            getSpreadsheet()?.resetSearchResult()
        }
        binding.editSearch.setOnEditorActionListener { v, actionId, event ->

            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // Perform your action here
                searchExcel()
                return@setOnEditorActionListener true
            }
            false
        }
        binding.flPre.setOnClickListener {
            getSpreadsheet()?.findBackward()
        }
        binding.flNext.setOnClickListener {
            getSpreadsheet()?.findForward()
        }
        lifecycleScope.launch {
            delay(3000)
            val ssControl: SSControl = (binding.mDocView.iOffice?.control?.appControl as SSControl)
            val sheetBar: SheetBar = ssControl.excelView.bar
            ssControl.actionEvent(EventConstant.SS_SHOW_SHEET, 0)
        }
    }

    private fun getSpreadsheet(): Spreadsheet? {
        val ssControl: SSControl? = (binding.mDocView.iOffice?.control?.appControl as SSControl?)
        return (ssControl?.find as Spreadsheet?)
    }

    private fun searchExcel() {

        val text = binding.editSearch.text
        if (text.isNullOrEmpty()) {
            return
        }
        val flag = getSpreadsheet()?.find(text.toString()) ?: false
        haveSearchResult = flag
        if (flag) {
            hideKeyboard(binding.editSearch)
            showBottomLayout()
        } else {
            binding.mDocView.visibility = View.GONE
        }
    }

    private var haveSearchResult: Boolean = false

    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 isSearchUI: Boolean = 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 fun showSearchUI() {
        isSearchUI = true
        binding.ivXuanzhuan.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
        hideKeyboard(binding.editSearch)
    }

    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-pathOrUri = $pathOrUri")
        LogEx.logDebug(TAG, "initData-docSourceType = $docSourceType")
        LogEx.logDebug(TAG, "initData-fileType = $fileType")

        SpStringUtils.addSpString(SpStringUtils.LAST_VIEW_KEY, (pathOrUri ?: "") + "_/_" + System.currentTimeMillis())
    }


}