package com.yidianling.ydlcommon.custom.base

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.tbruyelle.rxpermissions2.RxPermissions
import com.yidianling.ydlcommon.R
import com.yidianling.ydlcommon.custom.YdlBuryPointUtil
import com.yidianling.ydlcommon.custom.tool.StatusBarUtils
import com.yidianling.ydlcommon.custom.ui.LoadingDialogFragment

/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/01/27
 *
 * 若需要采用Lazy方式加载的Fragment，初始化内容放到 initDataAndEventLazy 实现
 * 若不需要Lazy加载则初始化内容放到 initDataAndEvent 即可
 *
 * 注意事项 1:
 * 如果是与ViewPager一起使用，调用的是setUserVisibleHint。
 *
 * 注意事项 2:
 * 如果是通过FragmentTransaction的show和hide的方法来控制显示，调用的是onHiddenChanged.
 * 针对初始就show的Fragment 为了触发onHiddenChanged事件 达到lazy效果 需要先hide再show
 */
abstract class BaseFragment : Fragment() {

    //Fragment的View加载完毕的标记
    private var isViewCreated: Boolean = false
    //Fragment对用户可见的标记
    private var isUIVisible: Boolean = false
    //Fragment 第一次加载的标记
    private var isFirstLoad: Boolean = false
    //是否有setUserVisibleHint方法
    private var isSetUserVisibleHint = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isFirstLoad = true
        //如果未调用过SetUserVisibleHint方法，则在此埋点，防止数据重复
        if (!isSetUserVisibleHint) {
            try {
                YdlBuryPointUtil.sendPv(this::class.java.simpleName)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val layoutResId = layoutResId()
        return when {
            layoutResId != 0 -> {
                val childView =   inflater.inflate(layoutResId, container, false)
                if (isAddStatusView()){
                    val containerView  =  inflater.inflate(R.layout.layout_root, container, false)
                    val rootView = containerView.findViewById<LinearLayout>(R.id.ll_root);
                    initStatus(rootView);
                    rootView.addView(childView)
                    return rootView
                }else{
                    return childView;
                }
            }
            else -> super.onCreateView(inflater, container, savedInstanceState)
        }
    }

    /**
     * 初始化状态栏
     */
    private fun initStatus(rootView:View) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            val statusView = rootView.findViewById<View>(R.id.view_status_place_holder)
            statusView.setBackgroundColor(Color.parseColor(getStatusColor()))
            val statusBarHeight = StatusBarUtils.getStatusBarHeight(activity)
            val layoutParams = statusView.getLayoutParams() as LinearLayout.LayoutParams
            layoutParams.height = statusBarHeight
            statusView.layoutParams = layoutParams
        }
    }

    protected lateinit var rootView: View

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isViewCreated = true
        rootView = view
        initDataAndEvent()
        lazyLoad()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        isUIVisible = isVisibleToUser
        isSetUserVisibleHint = true
        lazyLoad()
        if (isVisibleToUser) {
            try {
                YdlBuryPointUtil.sendPv(this::class.java.simpleName)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        isUIVisible = !hidden
        lazyLoad()

    }


    private fun lazyLoad() {
        if (isViewCreated && isUIVisible && isFirstLoad) {
            initDataAndEventLazy()
            //数据加载完毕,恢复标记,防止重复加载
            isFirstLoad = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        isSetUserVisibleHint = false
//        YdlRepository.getRefWatcher().watch(this)
    }


    // 请求运行时权限

    protected fun requestPermissions(callback: PermissionCallback, vararg permissions: String) {
        RxPermissions(activity).request(*permissions)
                .subscribe {
                    if (it) callback.onGranted()
                    else callback.onDenied()
                }
    }

    private var loadingDialogFragment: LoadingDialogFragment? = null

    protected fun showProgressDialog(msg: String) {
        if (loadingDialogFragment == null) {
            loadingDialogFragment = LoadingDialogFragment.Companion.newInstance(msg)
        }
        loadingDialogFragment?.show(childFragmentManager, null)
    }

    protected fun dismissProgressDialog() {
        if (loadingDialogFragment != null && loadingDialogFragment!!.isAdded) {
            loadingDialogFragment!!.hide()
            loadingDialogFragment = null
        }
    }


    @LayoutRes
    abstract fun layoutResId(): Int

    abstract fun initDataAndEvent()

    abstract fun initDataAndEventLazy()

    protected var callback: Callback? = null

    fun setCallback(callback: Callback): Fragment {
        this.callback = callback
        return this
    }

    open fun isAddStatusView(): Boolean{
        return false
    }

    open fun getStatusColor(): String{
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return "#FFFFFF"
        }
        return "#1da1f2"
    }

    // 用于单 fragment 的 activity 中用于替换 fragment 的接口
    interface Callback {

        fun replace(fragment: Fragment)
    }
}