package com.yidianling.home.ui.fragment

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.media.MediaPlayer
import android.text.TextUtils
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.tabs.TabLayout
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.base.BaseMvpFragment
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.Utils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.yidianling.consultant.OnBottomWordListener
import com.yidianling.consultant.api.IConsultantService
import com.yidianling.consultant.bean.FunctionWordConsultBean
import com.yidianling.home.R
import com.yidianling.home.adapter.YdlHomeAdapter
import com.yidianling.home.constants.HomeBIConstants
import com.yidianling.home.constract.HomeViewConfig
import com.yidianling.home.constract.IHomeContract
import com.yidianling.home.dialog.ActivityDialog
import com.yidianling.home.dialog.ActivityGuideDialog
import com.yidianling.home.event.HomeImpl
import com.yidianling.home.listener.HomeConfideRecyleSuspendListener
import com.yidianling.home.model.bean.*
import com.yidianling.home.presenter.HomePresenterImpl
import com.yidianling.home.ui.view.CouponDialog
import com.yidianling.home.ui.view.HomeSpaceItemDecoration
import com.yidianling.home.utils.HomeAnimUtils
import com.yidianling.user.api.service.IUserService
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.home_muse_view.*
import kotlinx.android.synthetic.ydl.home_fragment.*
import kotlinx.android.synthetic.ydl.home_fragment.tab_layout
import java.util.concurrent.TimeUnit


/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述: 壹点灵首页fragment
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/12
 */
@Route(path = "/home/home")
open class YdlHomeFragment : BaseMvpFragment<IHomeContract.View, HomePresenterImpl>(),
    IHomeContract.View,
    SwipeRefreshLayout.OnRefreshListener {
    private lateinit var mActivity:FragmentActivity
    private lateinit var mContext:Context
    open var adapter: YdlHomeAdapter? = null
    open var homeEvent: HomeImpl? = null
    open var dialog: CouponDialog? = null

    //双11活动弹窗
    open var aa: Dialog? = null


    /**
     * tablayou上次选中的tab下标
     */
    private var confideLastSelectPosition = 0
    private var confideLastSelectType = ""

    /**
     * TabLayout.OnTabSelectedListener
     */
    private var consultTabListener: TabLayout.OnTabSelectedListener? = null
    private var confideTabListener: TabLayout.OnTabSelectedListener? = null

    /**
     * 咨询tablayout上次选中的下标
     */
    private var consultLastSelectPosition = 0
    private var consultLastSelectType = ""

    /**
     * 悬浮tablayout监听事件
     */
    open lateinit var scrollListner: HomeConfideRecyleSuspendListener

    //咨询模块数据缓存
    private var consultCategoryDate: MutableList<HomeHeaderBean.ConsultCategoryDateBean>? = null

    open var searchText: String = ""
    open var doctorName: String = ""
    var startTime = 0L
    var endTime = 0L

    /**
     * 如果是第一次加载，则调用所有接口进行刷新，否则，只调用咨询和倾诉接口
     */
    private var isFromCreate: Boolean = true
    private lateinit var bottomWordlist: MutableList<FunctionWordConsultBean>
    var bottomWordDisposable: Disposable? = null

    override fun layoutResId(): Int {
        return R.layout.home_fragment
    }

    override fun initDataAndEvent() {
        mActivity = requireActivity()
        mContext = requireContext()
        initHomeEvent()
        initView()
        initTopButtonBanner()
        initAdapter()
    }

    open fun initHomeEvent() {
        homeEvent = HomeImpl(mActivity, this)
        getBottomWord()
    }

    private fun initAdapter() {
        mPresenter?.localHomeData(mContext, "home_data.json")
        adapter = homeEvent?.let { YdlHomeAdapter(mContext, it, ArrayList()) }
        val layoutManager = LinearLayoutManager(context)
        home_module_fragment_recycler.layoutManager = layoutManager
        home_module_fragment_recycler.adapter = adapter
        val space = resources.getDimension(R.dimen.platform_dp_24).toInt()
        home_module_fragment_recycler.addItemDecoration(HomeSpaceItemDecoration(space))
        initRvListener()
    }

    open fun initRvListener() {
        if (HomeViewConfig.getOrder().bannerIndex != -1) {
            homeEvent?.onPageScroll(
                view_rl_top_bg
            )?.let {
                home_module_fragment_recycler.addOnScrollListener(
                    it
                )
            }
        }
        scrollListner = HomeConfideRecyleSuspendListener()
        home_module_fragment_recycler.addOnScrollListener(scrollListner)
        setSuspendListener()
    }

    private fun initView() {
        if (HomeViewConfig.getOrder().bannerIndex == null || HomeViewConfig.getOrder().bannerIndex == -1) {
            var marginTop = this.resources.getDimension(R.dimen.home_home_title_bar_height)
            //4.4以下不支持状态栏变色
            val statusBarHeight = StatusBarUtils.getStatusBarHeight(mActivity)
            marginTop += statusBarHeight
            val lp = home_swipe_refresh_layout.layoutParams as FrameLayout.LayoutParams
            lp.topMargin = marginTop.toInt()
            home_swipe_refresh_layout.layoutParams = lp
        }
        searchText = this.resources.getText(R.string.home_search_hint).toString()
        home_swipe_refresh_layout?.setOnRefreshListener(this)
        home_swipe_refresh_layout?.setColorSchemeColors(
            ContextCompat.getColor(
                mContext,
                R.color.platform_main_theme
            )
        )
        home_swipe_refresh_layout?.setProgressViewOffset(false, 0, 200)
        home_service_call.setOnClickListener { homeEvent?.serviceCallClick() }
        initSearchBar()
        initStatus()
    }

    open fun initSearchBar() {
//        if (!TextUtils.isEmpty(doctorName)) {
//            searchText = doctorName
//        }
        home_tv.setOnClickListener {
            homeEvent?.searchTvClick(home_tv.text.toString())
        }

        iv_search_icon.setOnClickListener {
            homeEvent?.searchTvClick(searchText)
        }
//        home_tv.text = searchText
    }

    /**
     * 初始化状态栏位置
     */
    private fun initStatus() {
        //4.4以下不支持状态栏变色
        val statusBarHeight = StatusBarUtils.getStatusBarHeight(mActivity)
        val homeTitleBarHeight = resources.getDimension(R.dimen.home_home_title_bar_height)
        val lp1 = view_rl_top_bg.layoutParams as RelativeLayout.LayoutParams
        lp1.height = (homeTitleBarHeight + statusBarHeight).toInt()
        view_rl_top_bg.layoutParams = lp1

        val lp2 = rl_top.layoutParams as RelativeLayout.LayoutParams
        lp2.topMargin = statusBarHeight
        rl_top.layoutParams = lp2
    }

    override fun initDataAndEventLazy() {
    }

    /**
     * 设置顶部导航栏 功能点击事件
     */
    private fun initTopButtonBanner() {

        tv_consult.setOnClickListener {
            homeEvent?.reservationExpertsClick()
        }
        tv_confide.setOnClickListener {
            homeEvent?.nowConfideClick(adapter?.listenFree ?: false)
        }
        tv_course.setOnClickListener {
            homeEvent?.psychologyClassClick()
        }
        tv_test.setOnClickListener {
            homeEvent?.psychologyTestClick()
        }
        rl_backTop.setOnClickListener {
            home_module_fragment_recycler.scrollToPosition(0)
        }
    }

    override fun startAnim() {

    }

    override fun endAnim() {

    }

    override fun getSearchContent(): String {
        return searchText
    }

    override fun createPresenter(): HomePresenterImpl {
        return HomePresenterImpl()
    }

    override fun onRefresh() {
        home_swipe_refresh_layout.isRefreshing = true
        mPresenter?.refreshHomeData()
    }

    override fun resetModuleTabPosition() {
        adapter?.confideSelectPosition = 0
        adapter?.consultSelectPosition = 0
    }


    /**
     * 设置悬浮顶部监听数据
     */
    private fun setSuspendListener() {
        scrollListner.setContext(mContext)
        scrollListner.setHomeView(this)
        scrollListner.setConfideFilterView(ll_layout)
        scrollListner.setConsultFilterView(ll_consultLayout)
        adapter?.let { scrollListner.setSectionAdapter(it) }
        scrollListner.setPhoneCallImageView(home_service_call)
    }

    /**
     * 获取倾述列表数据
     * @param type 倾述类型
     * @param selectPosition 选中的position
     */
    override fun getConfideData(type: String, selectPosition: Int) {
        confideLastSelectPosition = selectPosition
        confideLastSelectType = type
        mPresenter?.getConfideData(type, selectPosition)
    }

    /**
     * 获取咨询列表数据
     */
    override fun getConsultData(type: String, selectPosition: Int) {
        consultLastSelectPosition = selectPosition
        consultLastSelectType = type
        mPresenter?.getConsultData(type, selectPosition)
    }

    override fun homeHeadResponse(homeHeaderBean: HomeHeaderBean) {
        //更新倾述列表数据
        adapter?.updateConfideFreeData(homeHeaderBean)
        //展示活动数据
        val act = homeHeaderBean.activityResponse

        act?.let { act ->
            if (!TextUtils.isEmpty(act.imageUrl)) {
                img_ad.visibility = View.VISIBLE
                ActionCountUtils.count(HomeBIConstants.YDL_HOME_SEARCH_TAG, act.title ?: "1")

                GlideApp.with(this).load(act.imageUrl).into(img_ad)
                img_ad.setOnClickListener {
                    if (Utils.isFastClick()) {
                        //防止连击
                        return@setOnClickListener
                    }
                    act.btnLinkurl?.let { btnLinkurl ->
                        if (btnLinkurl.startsWith("http")) {
                            NewH5Activity.start(activity, H5Params(btnLinkurl, null))
                        } else {
                            YDLRouterManager.router(btnLinkurl)
                        }
                        //定制咨询点击事件埋点
                        ActionCountUtils.count(
                            HomeBIConstants.YDL_HOME_SEARCH_TAG_CLICK,
                            act.title ?: "1"
                        )
                    }

                }
            } else {
                img_ad.visibility = View.GONE
            }

            if (!TextUtils.isEmpty(act.imageBanner)) {
                val va = SharedPreferencesEditor.getString(act.imageBanner)
                if (TextUtils.equals("yes", va)) {
                    //已经显示过，不再弹出
                    return
                }
            }

            if (!ModularServiceManager.provide(IUserService::class.java).isLogin()) {
                //未登录不显示
                return
            }
            if (!TextUtils.isEmpty(act.imageBanner)) {
                //展示弹窗
                if (aa == null) {
                    ActionCountUtils.count(HomeBIConstants.YDL_HOME_POPUPWINDOWS_PAGE_POPUP,act?.title ?: "1")
                    aa = ActivityDialog(mActivity, act.imageBanner, act.linkUrl, act.title)
                    aa?.show()
                    aa?.setOnDismissListener {
                        //文案不为空才显示引导--李思开
                        if (!TextUtils.isEmpty(act.title)) {
                            ActivityGuideDialog(mActivity, act.imageUrl, act.title).show()
                        }
                    }
                }
                //仅展示一次，以后不再展示
                SharedPreferencesEditor.putString(act.imageBanner, "yes")
            }
        }
    }

    override fun homeDataResponse(list: MutableList<HomePagerDataBean>) {
        home_swipe_refresh_layout.isRefreshing = false
        //更新首页数据
        adapter?.updateItems(list)
        if (!TextUtils.isEmpty(list[0].headerBean?.doctorName)) {
            doctorName = list[0].headerBean?.doctorName.toString()
            initSearchBar()
        }

        //每次全局更新后重置下标位
        confideLastSelectPosition = 0
        consultLastSelectPosition = 0
        //初始化fragment中的tablayout布局，悬停效果使用
        for (bean in list) {
            //咨询模块
            if (bean.type == HomeViewConfig.getOrder().bannerIndex) {
                initTabLayout(bean.headerBean?.listenCategoryDate)
                initConsultTabLayout(bean.headerBean?.consultCategoryData)
                consultLastSelectType = bean.headerBean?.consultCategoryData?.get(0)?.id.toString()
            }
        }
    }

    /**
     * 初始化fragment中的tablayout布局，悬停效果使用
     */
    private fun initTabLayout(listenCategoryDate: List<HomeHeaderBean.ListenCategoryDateBean>?) {
        if (confideTabListener == null) {
            confideTabListener =
                listenCategoryDate?.let { ConfideExpertTabSelectedListener(it, tab_layout) }
            tab_layout.addOnTabSelectedListener(confideTabListener)
        }

        tab_layout.removeAllTabs()
        if (listenCategoryDate != null) {
            for ((index, bean) in listenCategoryDate.withIndex()) {
                tab_layout.addTab(
                    tab_layout.newTab().setText(bean.name),
                    index == confideLastSelectPosition
                )
            }
        }
        var textView =
            ((tab_layout.getChildAt(0) as LinearLayout).getChildAt(confideLastSelectPosition) as LinearLayout).getChildAt(
                1
            )
        if (textView != null && textView is TextView) {
            textView.textSize = 17f
            textView.setTextColor(ContextCompat.getColor(mActivity, R.color.platform_color_242424))
            textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        }
    }

    /**
     * 初始化fragment中咨询tablayout布局，悬停效果使用
     */
    private fun initConsultTabLayout(listenCategoryDate: List<HomeHeaderBean.ConsultCategoryDateBean>?) {
        if (consultTabListener == null) {
            consultTabListener =
                listenCategoryDate?.let { ConsultExpertTabSelectedListener(it, tab_consultLayout) }
            tab_consultLayout.addOnTabSelectedListener(consultTabListener)
        }
        if (null == consultCategoryDate) {
            consultCategoryDate = ArrayList()
        }
        //如果 数据不变 则不重新构建

        if (null != listenCategoryDate && consultCategoryDate!!.size == listenCategoryDate.size && consultCategoryDate?.retainAll(
                listenCategoryDate
            ) == true
        ) {
            return
        }
        consultCategoryDate?.clear()
        if (null != listenCategoryDate) {
            consultCategoryDate?.addAll(listenCategoryDate)
        }
        tab_consultLayout.removeAllTabs()
        if (listenCategoryDate != null) {
            for ((index, bean) in listenCategoryDate.withIndex()) {
                tab_consultLayout.addTab(
                    tab_consultLayout.newTab().setText(bean.name),
                    index == confideLastSelectPosition
                )
            }
        }

        val textView = ((tab_consultLayout.getChildAt(0) as LinearLayout).getChildAt(
            confideLastSelectPosition
        ) as LinearLayout).getChildAt(1)
        if (textView != null && textView is TextView) {
            textView.textSize = 17f
            textView.setTextColor(ContextCompat.getColor(mActivity, R.color.platform_color_242424))
            textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        }
    }

    override fun confideDataResponse(data: HomeConfideBean, selectPosition: Int) {
        //更新倾述列表数据
        adapter?.updateConfideData(data, selectPosition)
    }

    override fun consultDataResponse(data: HomeConsultBean, selectPosition: Int) {
        //更新咨询列表数据
        adapter?.updateConsultData(data, selectPosition)
    }

    override fun askDataResponse(data: HomeAskBean, position: Int) {
        //更新问答模块数据
        adapter?.updateAskData(data, position)
    }

    override fun homeDataFail(msg: String) {
        home_swipe_refresh_layout?.isRefreshing = false
//        ToastHelper.show(msg)
    }

    override fun askZan(position: Int, index: Int, id: String) {
        mPresenter?.askZan(position, index, id)
    }

    override fun askFocus(position: Int, id: String) {
        mPresenter?.askFocus(position, id)
    }

    override fun showHomeProgress() {
        showHomeProgress()
    }

    override fun showRefreshLayout() {
        home_swipe_refresh_layout?.isRefreshing = true
    }

    override fun dismissHomeProgress() {
        dismissHomeProgress()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && isResumed) {
            startTime=System.currentTimeMillis()
        } else {
            if (startTime!=0L){
                endTime=System.currentTimeMillis()
                ActionCountUtils.count(HomeBIConstants.YDL_HOME_DWELL_TIME,(endTime-startTime).toString())
                startTime=0L
            }

        }
        if (isVisibleToUser && isResumed) {
            onResume()
        }
    }

    private fun getBottomWord() {
        ModularServiceManager.provide(IConsultantService::class.java)
            .getbottomWord(2, object : OnBottomWordListener {
                override fun onBottomWord(wordList: MutableList<FunctionWordConsultBean>) {
                    bottomWordlist = wordList
                    if (bottomWordlist.isNullOrEmpty()) return
                    if (bottomWordlist.size == 1) {
                        home_tv.text = bottomWordlist[0].word
                    } else {
                        if (bottomWordDisposable != null) {
                            bottomWordDisposable?.dispose()
                        } else {
                            bottomWordDisposable = Observable.interval(0, 3, TimeUnit.SECONDS)
                                .subscribeOn(Schedulers.computation())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe({
                                    home_tv.text =
                                        bottomWordlist[(it % bottomWordlist.size).toInt()].word
                                }, {
                                }, {

                                })
                        }
                    }
                }

            })
    }

    private fun hideConsultAssistantDialog() {
        ModularServiceManager.provide(IConsultantService::class.java).hideConsultAssistantDialog()
    }


    override fun onResume() {
        super.onResume()
        if (userVisibleHint) {
            if (isFromCreate) {
                isFromCreate = false
                mPresenter?.loadHomeData()
            } else {
                mPresenter?.loadHomeData()
                mPresenter?.getConsultData(consultLastSelectType, consultLastSelectPosition)
                mPresenter?.getConfideData(confideLastSelectType, confideLastSelectPosition)
            }
            ActionCountUtils.count(HomeBIConstants.YDL_USER_MAIN_PAGE_VISIT)
            ActionCountUtils.count("daoyi_advertisement_page|daoyi_advertisement_visit","1")

            video_view?.setOnInfoListener { mp, what, extra ->
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START){
                    video_view?.setBackgroundColor(Color.TRANSPARENT)
                }
                true
            }
            video_view?.start()
        }
    }

    override fun onPause() {
        super.onPause()
        if (startTime!=0L){
            endTime=System.currentTimeMillis()
            ActionCountUtils.count(HomeBIConstants.YDL_HOME_DWELL_TIME,(endTime-startTime).toString())
            startTime=0L
        }
        video_view?.pause()
    }

    /**
     * 咨询楼层tablayout
     */
    inner class ConsultExpertTabSelectedListener : TabLayout.OnTabSelectedListener {
        private var list: List<HomeHeaderBean.ConsultCategoryDateBean>? = null
        private var tabLayout: TabLayout? = null

        constructor(list: List<HomeHeaderBean.ConsultCategoryDateBean>, tabLayout: TabLayout) {
            this.list = list
            this.tabLayout = tabLayout
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
            var textView =
                (tab?.position?.let { (tabLayout?.getChildAt(0) as LinearLayout).getChildAt(it) } as LinearLayout).getChildAt(
                    1
                )
            if (textView != null && textView is TextView) {
                textView.textSize = 15f
                activity?.let {
                    ContextCompat.getColor(
                        it,
                        R.color.platform_color_333333
                    )
                }?.let {
                    textView.setTextColor(
                        it
                    )
                }
            }
        }

        override fun onTabSelected(tab: TabLayout.Tab?) {
            if (tab?.position == consultLastSelectPosition) {
                return
            }
            var textView =
                (tab?.position?.let { (tabLayout?.getChildAt(0) as LinearLayout).getChildAt(it) } as LinearLayout).getChildAt(
                    1
                )
            if (textView != null && textView is TextView) {
                textView.textSize = 17f
                activity?.let {
                    ContextCompat.getColor(
                        it,
                        R.color.platform_color_242424
                    )
                }?.let {
                    textView.setTextColor(
                        it
                    )
                }
                textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            }
            list?.get(tab.position)?.let { homeEvent?.getConsultData(it, tab.position) }
        }
    }

    inner class ConfideExpertTabSelectedListener : TabLayout.OnTabSelectedListener {
        private var list: List<HomeHeaderBean.ListenCategoryDateBean>? = null
        private var tabLayout: TabLayout? = null

        constructor(list: List<HomeHeaderBean.ListenCategoryDateBean>, tabLayout: TabLayout) {
            this.list = list
            this.tabLayout = tabLayout
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
            var textView =
                (tab?.let { (tabLayout?.getChildAt(0) as LinearLayout).getChildAt(it.position) } as LinearLayout).getChildAt(
                    1
                )
            if (textView != null && textView is TextView) {
                textView.textSize = 15f
                activity?.let {
                    ContextCompat.getColor(
                        it,
                        R.color.platform_color_333333
                    )
                }?.let {
                    textView.setTextColor(
                        it
                    )
                }
            }
        }

        override fun onTabSelected(tab: TabLayout.Tab?) {
            if (tab?.position == confideLastSelectPosition) {
                return
            }

            var textView =
                (tab?.let { (tabLayout?.getChildAt(0) as LinearLayout).getChildAt(it.position) } as LinearLayout).getChildAt(
                    1
                )
            if (textView != null && textView is TextView) {
                textView.textSize = 17f
                activity?.let {
                    ContextCompat.getColor(
                        it,
                        R.color.platform_color_242424
                    )
                }?.let {
                    textView.setTextColor(
                        it
                    )
                }
                textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            }

            val minus = list?.size ?: -1
            if (minus != -1 && tab.position < minus) {
                list?.get(tab.position)?.let { homeEvent?.getConfideData(it, tab.position) }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        HomeAnimUtils.clear()
        bottomWordDisposable?.dispose()
    }
}