package com.convenient.android.common.base.view

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.fragment.app.Fragment
import com.orhanobut.logger.Logger

/**
 *    @author : HuBoWen
 *    @date   : 2020/9/14  3:55 PM
 *    @description：基础Fragment
 */
open class BaseFragment : Fragment() {

    companion object {
        const val STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN"
    }

    /**
     * 上下文
     *
     */
    private var context: Context? = null

    /**
     *  是否与View建立起映射关系
     *
     */
    private var isInitView = false

    /****** 是否是第一次加载数据  */
    private var isFirstLoad = true

    var handler: Handler? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        this.context = context
    }

    override fun getContext() = context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /****** 解决Fragment重叠问题 备注：
         * 这里一定要在save为null时才加载Fragment，Fragment中onCreateView等生命周里加载根子Fragment同理
         * 因为在页面重启时，Fragment会被保存恢复，而此时再加载Fragment会重复加载，导致重叠，所有activity中increase（）
         * if(findFragmentByTag(rootFragmentTag) == null){
         * 正常情况下去 加载根Fragment
         * } */
        runCatching {
            savedInstanceState?.let {
                when {
                    (savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN)) -> childFragmentManager.beginTransaction().hide(this)
                    else -> childFragmentManager.beginTransaction().show(this)
                }
                childFragmentManager.beginTransaction().commit()
            }
            handler = Handler(Looper.getMainLooper())
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        /****** 自己保存Fragment的Hidden状态*/
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        getView()?.let {
            isInitView = true
            onInitView()
            onInitData()
        }
    }

    protected open fun onInitView() {}

    protected open fun onInitData() {
        isFirstLoad = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        isInitView = false
        isFirstLoad = true
        if (isRemoving) Logger.t("baseFragment").d(javaClass.simpleName + " : onDestroyView! ")
    }

    override fun onDestroy() {
        super.onDestroy()
        handler?.removeCallbacksAndMessages(null)
        handler = null
        if (isRemoving) Logger.t("baseFragment").d(javaClass.simpleName + " : onDestroy! ")
    }

    open fun onBackPressed() {}


}