package com.yidianling.home.ui.fragment

import android.app.Dialog
import android.graphics.Typeface
import android.os.Build
import android.support.design.widget.TabLayout
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
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 com.alibaba.android.arouter.facade.annotation.Route
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.api.IConsultantService
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 kotlinx.android.synthetic.ydl.home_fragment.*


/**
 * @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 {

    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 var scrollListner: HomeConfideRecyleSuspendListener? = null
    //咨询模块数据缓存
    private var consultCategoryDate: MutableList<HomeHeaderBean.ConsultCategoryDateBean>? = null

    open var searchText: String = ""
    open var doctorName: String = ""

    /**
     * 如果是第一次加载,则调用所有接口进行刷新,否则,只调用咨询和倾诉接口
     */
    private var isFromCreate: Boolean = true

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

    override fun initDataAndEvent() {
//        val homeViewOrder = HomeViewConfig.HomeViewOrder()
//
//        homeViewOrder.bannerIndex = -1
//        homeViewOrder.testsIndex = 1
//        homeViewOrder.consultIndex = 2
//        homeViewOrder.footerIndex = 3
//
//        homeViewOrder.fmIndex = null
//        homeViewOrder.articleIndex = null
//        homeViewOrder.dynamicIndex = null
//        homeViewOrder.museIndex = null
//        homeViewOrder.confideIndex = null
//        homeViewOrder.courseIndex = null
//        homeViewOrder.buttonIndex = null
//
//        HomeViewConfig.setOrder(homeViewOrder)

        initHomeEvent()
        initView()
        initTopButtonBanner()
        initAdapter()
    }

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

    private fun initAdapter() {
        mPresenter?.localHomeData(this.context, "home_data.json")
        adapter = YdlHomeAdapter(context, homeEvent!!, 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){
            home_module_fragment_recycler.addOnScrollListener(homeEvent?.onPageScroll(view_rl_top_bg))
        }
        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)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4以下不支持状态栏变色
                val statusBarHeight = StatusBarUtils.getStatusBarHeight(activity)
                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(context, 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(searchText) }
        home_tv.text = searchText
    }

    /**
     * 初始化状态栏位置
     */
    private fun initStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4以下不支持状态栏变色
            val statusBarHeight = StatusBarUtils.getStatusBarHeight(activity)
            var 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()
        }
        tv_course.setOnClickListener {
            homeEvent?.psychologyClassClick()
        }
        tv_test.setOnClickListener {
            homeEvent?.psychologyTestClick()
        }
        rl_backTop.setOnClickListener {
            home_module_fragment_recycler.scrollToPosition(0)
        }
    }
    override fun startAnim() {
        HomeAnimUtils.startAnim(context, rl_top, rl_search, home_service_call, home_tv)
        HomeAnimUtils.startSearchShow(ll_top_function, view_search_input_bg, home_tv, iv_search_icon, img_ad)
    }

    override fun endAnim() {
        HomeAnimUtils.endAnim(context, rl_top, rl_search, home_tv, home_service_call, this)
        HomeAnimUtils.startSearchHide(ll_top_function, view_search_input_bg, home_tv, iv_search_icon, img_ad)
    }

    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(context)
        scrollListner?.setHomeView(this)
        scrollListner?.setConfideFilterView(ll_layout)
        scrollListner?.setConsultFilterView(ll_consultLayout)
        scrollListner?.setSectionAdapter(adapter!!)
        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) {
        //展示活动数据
        val act = homeHeaderBean.activityResponse

        if (act != null) {
            if (!TextUtils.isEmpty(act!!.imageUrl)) {
                img_ad.visibility = View.VISIBLE
                GlideApp.with(this).load(act!!.imageUrl).into(img_ad)
                img_ad.setOnClickListener {
                    if (Utils.isFastClick()) {
                        //防止连击
                        return@setOnClickListener
                    }
                    if (act.btnLinkurl != null && act.btnLinkurl!!.startsWith("http")) {
                        NewH5Activity.start(activity, H5Params(act.btnLinkurl!!, null))
                    } else {
                        YDLRouterManager.router(act.btnLinkurl)
                    }
                }
            } 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) {
                    aa = ActivityDialog(activity, act.imageBanner, act.linkUrl, act.title)
                    aa?.show()
                    aa?.setOnDismissListener {
                        //文案不为空才显示引导--李思开
                        if (!TextUtils.isEmpty(act.title)){
                            ActivityGuideDialog(activity, 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!!
            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!![0].id.toString()
            }
        }
    }

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

        tab_layout.removeAllTabs()
        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(activity, R.color.platform_color_242424))
            textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        }
    }

    /**
     * 初始化fragment中咨询tablayout布局,悬停效果使用
     */
    private fun initConsultTabLayout(listenCategoryDate: List<HomeHeaderBean.ConsultCategoryDateBean>?) {
        if (consultTabListener == null) {
            consultTabListener = ConsultExpertTabSelectedListener(listenCategoryDate!!, tab_consultLayout)
            tab_consultLayout.addOnTabSelectedListener(consultTabListener!!)
        }
        if (null == consultCategoryDate) {
            consultCategoryDate = ArrayList()
        }
        //如果 数据不变 则不重新构建
        if (null != listenCategoryDate && consultCategoryDate!!.size == listenCategoryDate.size && consultCategoryDate!!.retainAll(listenCategoryDate)) {
            return
        }
        consultCategoryDate?.clear()
        if (null != listenCategoryDate) {
            consultCategoryDate?.addAll(listenCategoryDate)
        }
        tab_consultLayout.removeAllTabs()
        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(activity, 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) {
            showConsultAssistantDialog()
        } else {
            hideConsultAssistantDialog()
        }
        if (isVisibleToUser && isResumed) {
            onResume()
        }
    }

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

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

    override fun onResume() {
        super.onResume()
        if (userVisibleHint) {
            ActionCountUtils.count(HomeBIConstants.YDL_USER_MAIN_PAGE_VISIT)

            if (isFromCreate) {
                isFromCreate = false
                mPresenter?.loadHomeData()
            }else {
                mPresenter?.getConsultData(consultLastSelectType, consultLastSelectPosition)
                mPresenter?.getConfideData(confideLastSelectType, confideLastSelectPosition)
            }

            showConsultAssistantDialog()
        }
    }

    /**
     * 咨询楼层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 = ((tabLayout!!.getChildAt(0) as LinearLayout).getChildAt(tab!!.position) as LinearLayout).getChildAt(1)
            if (textView != null && textView is TextView) {
                textView.textSize = 15f
                textView.setTextColor(ContextCompat.getColor(activity, R.color.platform_color_333333))
            }
        }

        override fun onTabSelected(tab: TabLayout.Tab?) {
            if (tab!!.position == consultLastSelectPosition) {
                return
            }
            var textView = ((tabLayout!!.getChildAt(0) as LinearLayout).getChildAt(tab!!.position) as LinearLayout).getChildAt(1)
            if (textView != null && textView is TextView) {
                textView.textSize = 17f
                textView.setTextColor(ContextCompat.getColor(activity, R.color.platform_color_242424))
                textView.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
            }
            homeEvent!!.getConsultData(list!![tab!!.position], 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 = ((tabLayout!!.getChildAt(0) as LinearLayout).getChildAt(tab!!.position) as LinearLayout).getChildAt(1)
            if (textView != null && textView is TextView) {
                textView.textSize = 15f
                textView.setTextColor(ContextCompat.getColor(activity, R.color.platform_color_333333))
            }
        }

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

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

    override fun onDestroyView() {
        super.onDestroyView()
        HomeAnimUtils.clear()
    }
}