package com.ydl.ydlcommon.base

import android.app.Activity
import android.content.res.Resources
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import com.trello.rxlifecycle2.android.ActivityEvent
import com.ydl.ydlcommon.R
import com.ydl.ydlcommon.base.lifecycle.IActivityLifecycleable
import com.ydl.ydlcommon.bean.StatusBarOptions
import com.ydl.ydlcommon.ui.LoadingDialogFragment
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.AndroidSystemHelper
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.statusBar.StatusBarUtil
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlin.properties.Delegates

/**
 * 基础 Activity，所有的 Activity 都继承此类
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/01/27
 */
abstract class BaseActivity : AppCompatActivity(), IActivityLifecycleable {

    private val mLifecycleSubject = BehaviorSubject.create<ActivityEvent>()
    var mContext: Activity by Delegates.notNull()
    var statusView: View? = null
    private var loadingDialogFragment: LoadingDialogFragment? = null

    override fun provideLifecycleSubject(): Subject<ActivityEvent> {
        return mLifecycleSubject;
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        //修复Android 8.0 崩溃
        AndroidSystemHelper.fixAndroidOrientationBug(this)
        setImmersiveStatusBar()
        super.onCreate(savedInstanceState)

        Log.d("TAG", javaClass.name)
        mContext = this

        val layoutResId = layoutResId()
        if (layoutResId != 0) setContentView(layoutResId())
        ActivityManager.getInstance().addStack(this)
        initDataAndEvent()
    }

    /**
     * 开启沉浸式状态栏
     * 默认关闭
     */
    open fun turnOnImmersiveStatusBar() = false

    /**
     * true: 黑色字体
     * false: 白色字体
     */
    open fun setStatusBarBlackFont() = false

    private fun setImmersiveStatusBar() {
        if (turnOnImmersiveStatusBar()) {
            StatusBarUtil.setTranslucent(window)
            if (setStatusBarBlackFont())
                StatusBarUtil.statusBarDarkMode(this)
            else
                StatusBarUtil.statusBarLightMode(this)
        }
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        if (AndroidSystemHelper.isAllowSetOrientation(this)) {
            super.setRequestedOrientation(requestedOrientation)
        }
    }

    override fun setContentView(@LayoutRes layoutResID: Int) {
        if (getStatusViewOptions().isAddStatusView) {
            val options = getStatusViewOptions()
            options.bottomStatusColor = getDefaultBottomColor()
            val returnViews =
                StatusBarUtils.initStatusBarView(this, layoutResID, getStatusViewOptions())

            if (returnViews.size > 1) {
                statusView = returnViews[1];
            }

            super.setContentView(returnViews[0])
            AndroidSystemHelper.fixAndroidBug5497Workaround(this)
        } else {

            //判定是否有底部小横条
            if (StatusBarUtils.hasBottomNavigatorLine(this)) {
                val containerView =
                    View.inflate(this, R.layout.platform_layout_bottom_fit_root, null) as ViewGroup
                val rootView = containerView.findViewById<FrameLayout>(R.id.ll_bottom_fit_root);
                val layoutView = View.inflate(this, layoutResID, null)

                val params =
                    ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )

                rootView.addView(layoutView, params)

                val bottomView = containerView.findViewById<View>(R.id.ll_bottom_fit_v)
                bottomView.visibility = View.VISIBLE
                bottomView.setBackgroundColor(getDefaultBottomColor())

                super.setContentView(containerView)
            } else {
                super.setContentView(layoutResID)
            }
        }
    }

    /**
     * 设置底部抬高的布局的颜色
     */
    open fun setBottomColor(color: String) {
        try {
            if (getStatusViewOptions()?.isAddStatusView) {
                if (StatusBarUtils.hasBottomNavigatorLine(this)) {
                    findViewById<View>(R.id.ll_bottom_v).setBackgroundColor(
                        Color.parseColor(
                            color
                        )
                    )
                }
            } else {
                if (StatusBarUtils.hasBottomNavigatorLine(this)) {
                    findViewById<View>(R.id.ll_bottom_fit_v).setBackgroundColor(
                        Color.parseColor(
                            color
                        )
                    )
                }
            }
        } catch (e: Exception) {
        }
    }

    open fun getDefaultBottomColor(): Int {
        return Color.parseColor("#00000000")
    }

    override fun onDestroy() {
        super.onDestroy()
        ActivityManager.getInstance().removeStack(this)
        AndroidSystemHelper.fixInputMethodManagerLeak(this)
    }

    @LayoutRes
    protected abstract fun layoutResId(): Int

    // 初始化数据和事件
    protected abstract fun initDataAndEvent()

    override fun getResources(): Resources {
        //解决 修改系统字体大小后 H5页面大小比例不正常现象
        val res = super.getResources()
        return AndroidSystemHelper.fixResourcesScale(res)
    }

    open fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions()
    }


    fun showProgressDialog() {
        showProgressDialog("")
    }


    //显示dialog
    open fun showProgressDialog(str: String?) {
        if (loadingDialogFragment == null) {
            loadingDialogFragment = LoadingDialogFragment.newInstance(str)
        }
        if (loadingDialogFragment?.isAdded!!) {
            return
        }
        loadingDialogFragment?.show(supportFragmentManager, BaseActivity::class.java.simpleName)
    }

    //移除dialog
    open fun dismissProgressDialog() {
        try {
            if (loadingDialogFragment != null && loadingDialogFragment?.isAdded!!) {
                loadingDialogFragment?.hide()
                loadingDialogFragment = null
            }
        } catch (e: Exception) {
            //防止以下错误
            //java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
        }

    }

    /**
     * 展示 Fragment
     * 防止崩溃异常 -> java.lang.IllegalStateException: Fragment already added
     */
    fun showFragment(dialogFragment: DialogFragment?, tag: String) {
        dialogFragment?.let {
            val transaction = supportFragmentManager.beginTransaction()
            if (it.isAdded && supportFragmentManager.findFragmentByTag(tag) != null) {
                transaction.show(it)
            } else {
                supportFragmentManager.executePendingTransactions()
                transaction.remove(dialogFragment) // 避免 Fragment already added
                transaction.add(it, tag)
            }
            transaction.commitAllowingStateLoss()
        }
    }

}