package cn.yyxx.eyuangame.core.impl.center

import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import cn.yyxx.eyuangame.core.impl.SdkBridgeImpl
import cn.yyxx.eyuangame.core.impl.center.fragment.BindAccountFragment
import cn.yyxx.eyuangame.core.impl.center.fragment.BindPhoneFragment
import cn.yyxx.eyuangame.core.impl.center.fragment.MainFragment
import cn.yyxx.eyuangame.core.impl.center.fragment.ModifyPwdFragment
import cn.yyxx.eyuangame.core.utils.TimeDownUtils
import cn.yyxx.support.AndroidBug5497Workaround
import cn.yyxx.support.ResUtils
import java.util.*

/**
 * @author #Suyghur.
 * Created on 2021/06/30
 */
class MemberActivity : FragmentActivity() {

    private var mainFragment: MainFragment? = null
    private var bindAccountFragment: BindAccountFragment? = null
    private var bindPhoneFragment: BindPhoneFragment? = null
    private var modifyPwdFragment: ModifyPwdFragment? = null

    private val fragmentStack = LinkedList<String>()
    private var currentFragmentTag = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        initFragment()
    }

    private fun initView() {
        if (SdkBridgeImpl.isLand) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        }
        setContentView(ResUtils.getResId(this, "yyxx_member", "layout"))

        if (!SdkBridgeImpl.isLand) {
            AndroidBug5497Workaround.assistActivity(this)
        }

    }

    private fun initFragment() {
        mainFragment = MainFragment()
        switchFragment(mainFragment!!, MemberFragmentTag.MAIN)
    }

    fun switchFragment(tag: String) {
        when (tag) {
            MemberFragmentTag.MAIN -> {
                mainFragment?.apply {
                    mainFragment = null
                }
                mainFragment = MainFragment()
                switchFragment(mainFragment!!, tag)
            }
            MemberFragmentTag.BIND_ACCOUNT -> {
                bindAccountFragment?.apply {
                    bindAccountFragment = null
                }
                bindAccountFragment = BindAccountFragment()
                switchFragment(bindAccountFragment!!, tag)
            }
            MemberFragmentTag.BIND_PHONE -> {
                bindPhoneFragment?.apply {
                    bindPhoneFragment = null
                }
                bindPhoneFragment = BindPhoneFragment()
                switchFragment(bindPhoneFragment!!, tag)
            }
            MemberFragmentTag.MODIFY_PWD -> {
                modifyPwdFragment?.apply {
                    modifyPwdFragment = null
                }
                modifyPwdFragment = ModifyPwdFragment()
                switchFragment(modifyPwdFragment!!, tag)
            }
        }
    }

    fun switchFragment(fragment: Fragment, tag: String) {
        if (fragmentStack.contains(tag)) {
            //栈里最后一个与tag相同才执行删除
            if (fragmentStack.size > 1 && !fragmentStack.last.equals(tag)) {
                fragmentStack.removeLast()
            }
        } else {
            fragmentStack.add(tag)
        }

        val transaction = supportFragmentManager.beginTransaction()
        transaction.setCustomAnimations(ResUtils.getResId(this, "yyxx_fragment_push_anim", "anim"), ResUtils.getResId(this, "yyxx_fragment_popup_anim", "anim"))
        var tagFragment = supportFragmentManager.findFragmentByTag(currentFragmentTag)
        if (tagFragment != null && tag != currentFragmentTag) {
            tagFragment.onPause()
            transaction.hide(tagFragment)
        }
        tagFragment = supportFragmentManager.findFragmentByTag(tag)
        if (tagFragment == null) {
            transaction.add(ResUtils.getResId(this, "yyxx_cl_member_center", "id"), fragment, tag)
        } else {
            tagFragment.onResume()
            transaction.show(tagFragment)
        }

        currentFragmentTag = tag
        transaction.commitAllowingStateLoss()

    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        ev?.let {
            if (it.action == MotionEvent.ACTION_DOWN) {
                val v = currentFocus
                if (isShouldHideInput(v, it)) {
                    val imm = this@MemberActivity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v!!.windowToken, 0)
                }
                return super.dispatchTouchEvent(it)
            }
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else onTouchEvent(ev)
    }

    private fun hideBar() {
        // The UI options currently enabled are represented by a bitfield.
        // getSystemUiVisibility() gives us that bitfield.
        val uiOptions = window.decorView.systemUiVisibility
        var newUiOptions = uiOptions
        val isImmersiveModeEnabled = uiOptions or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY == uiOptions
        if (!isImmersiveModeEnabled) {
            if (Build.VERSION.SDK_INT >= 14) {
                newUiOptions = newUiOptions or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            }
            if (Build.VERSION.SDK_INT >= 16) {
                newUiOptions = newUiOptions or View.SYSTEM_UI_FLAG_FULLSCREEN
            }
            if (Build.VERSION.SDK_INT >= 18) {
                newUiOptions = newUiOptions or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            }
            window.decorView.systemUiVisibility = newUiOptions
        }
    }


    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v is EditText) {
            val leftTop = intArrayOf(0, 0)
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop)
            val left = leftTop[0]
            val top = leftTop[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            // 点击的是输入框区域，保留点击EditText的事件
            return event.x <= left || event.x >= right || event.y <= top || event.y >= bottom
        }
        return false
    }


    override fun onResume() {
        super.onResume()
        hideBar()
    }

    override fun onDestroy() {
        super.onDestroy()
        TimeDownUtils.cancel()
    }

    override fun onBackPressed() {
        if (!fragmentStack.isNullOrEmpty() && fragmentStack.size > 1) {
            fragmentStack.removeLast()
            switchFragment(fragmentStack.last)
        } else {
            super.onBackPressed()
        }
    }

    companion object {
        fun start(activity: Activity) {
            activity.startActivity(Intent(activity, MemberActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        }
    }
}