package com.ydl.confide.home

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.interfaces.DraweeController
import com.jcodecraeer.xrecyclerview.ProgressStyle
import com.jcodecraeer.xrecyclerview.XRecyclerView
import com.ydl.confide.R
import com.ydl.confide.api.ConfideRoute
import com.ydl.confide.home.adapter.ConfideHomeAdapter
import com.ydl.confide.home.bean.ConfideHomeAllFiltersBean
import com.ydl.confide.home.bean.ConfideHomeBodyBean
import com.ydl.confide.home.bean.ConfideHomeDataBean
import com.ydl.confide.home.bean.ConfideHomeFiterItemBean
import com.ydl.confide.home.config.IConfideHomeConfig
import com.ydl.confide.home.contract.IConfideHomeContract
import com.ydl.confide.home.event.ConfideHomeEventImpl
import com.ydl.confide.home.event.IConfideHomeEvent
import com.ydl.confide.home.listener.ConfideHomeRecycleViewListener
import com.ydl.confide.home.listener.ConfideHomeRecyleSuspendListener
import com.ydl.confide.home.modular.service.ConfideWebServiceImpl
import com.ydl.confide.home.presenter.ConfideHomePresenterImpl
import com.ydl.confide.home.util.ConfideHomeUtils
import com.ydl.confide.home.widget.FilterItemDecoration
import com.ydl.confide.intro.VideoViewModel
import com.ydl.confide.router.PhoneCallIn
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.listener.YDLImageRecyclerOnScrollListener
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.base.config.HttpConfig.Companion.YDL_H5
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.mvp.lce.BaseLceActivity
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.ydl.ydlcommon.view.DrawableRightTextView
import com.ydl.ydlcommon.view.WrapContentLinearLayoutManager
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.im.api.service.IImService
import com.yidianling.user.api.service.IUserService
import kotlinx.android.synthetic.main.confide_home_activity.*
import kotlinx.android.synthetic.main.confide_title_bar.*

/**
 * @author yuanwai
 * @描述:倾诉首页Activity
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/8/10
 */
@Route(path = ConfideRoute.R_CONFIDE_HOME)
class ConfideHomeActivity :
    BaseLceActivity<IConfideHomeContract.View, IConfideHomeContract.Presenter>(),
    IConfideHomeContract.View, XRecyclerView.LoadingListener {

    private var listenFree = false

    override fun getContentViewId(): Int {
        return R.id.rv_list
    }

    override fun getStateViewId(): Int {
        return R.id.lce_state_view
    }

    override fun reLoadData() {

    }


    //是否从启动页直接进入
    var isSplash: Boolean = false

    /**
     * 倾诉首页适配器
     */
    private var mConfideAdapter: ConfideHomeAdapter? = null

    /**
     * 倾诉首页事件处理类
     */
    private var mConfideEvent: IConfideHomeEvent? = null

    /**
     * 数据缓存
     */
    private var cacheList: MutableList<ConfideHomeDataBean>? = null

    // 一键倾诉Url
    private var quickConsultUrl: String? = null

    /**
     * 页（从第二页开始）
     */
    private var page: Int = 1

    //筛选参数bean
    private var allFiltersBean: ConfideHomeAllFiltersBean? = null

    //用于置顶筛选模块监听
    private var listScrollListener: ConfideHomeRecycleViewListener? = null

    //用于显示筛选悬浮View
    private var listSuspendListener: ConfideHomeRecyleSuspendListener? = null

    //是否有下一页（用于判断为你推荐条数，如果首页返回少于10条 那么就可以认为没有下一页了） 默认有下一页
    private var hasMore = true
    private var dp48 = 0
    private var bottomSheetDialogFragment: ConfideBottomSheetDialogFragment? = null

    init {
        //初始化参数
        initParam()
        dp48 = RxImageTool.dip2px(48f)
    }

    private fun initParam() {
        allFiltersBean = ConfideHomeAllFiltersBean(
            page,
            ConfideHomeFiterItemBean("1", ""),
            ConfideHomeFiterItemBean("-1", ""),
            ArrayList(),
            ArrayList()
        )
    }

    override fun getContext(): Context {
        return ConfideHomeActivity@ this
    }

    override fun createPresenter(): IConfideHomeContract.Presenter {
        return ConfideHomePresenterImpl()
    }

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

    /**
     * 下拉刷新回调
     */
    override fun onRefresh() {
        //重置页
        page = 1
        allFiltersBean!!.page = page
        clearCacheData()
        mPresenter.confideHomeRequest(true)
        recommendList(page)
    }

    /**
     * 上拉加载更多
     */
    override fun onLoadMore() {
        recommendList(page + 1)
    }

    override fun recommendList(page: Int) {
        //需要将当前列表已存在的老师uid数组发送到后端去重，因为排序实时变化
        this.page = page
        allFiltersBean!!.page = page
        if (1 == page) {
            //显示加载中
            showProgressDialog()
            allFiltersBean!!.notInUid = ArrayList()
            mPresenter.recommendList(ConfideHomeUtils.createParam(allFiltersBean!!))
        } else if (page > 1) {
            var listData = mConfideAdapter?.getList()
            var notUidList = ArrayList<Int>()
            if (listData != null) {
                for (bean in listData) {
                    //列表类型数组
                    if (bean.type == 5 && bean.body != null) {
                        for (bean in bean.body) {
                            notUidList.add(bean.uid ?: 0)
                        }
                    }
                }
            }
            allFiltersBean!!.notInUid = notUidList
            mPresenter.recommendListMore(ConfideHomeUtils.createParam(allFiltersBean!!))
        }
    }

    override fun initDataAndEvent() {
        //来自首页倾诉红包入口
        val isFromRed = intent.getBooleanExtra(IYDLRouterConstant.EXTRA_RED_PACKET, false)
        val confidedId = intent.getStringExtra(IYDLRouterConstant.EXTRA_CONFIDEDID)
        val doctorId = intent.getStringExtra(IYDLRouterConstant.EXTRA_DOCTORID)

        isSplash = intent.getBooleanExtra("isSplash", false)
        //初始化View
        initView()
        mConfideEvent = ConfideHomeEventImpl(this, this)
        //初始化适配器
        initAdapter()
        //显示加载中
//        showProgressDialog()
        //加载本地缓存
//        mPresenter.loadLocalData(this)
        rv_list.refresh()
        initClick()
        initQuickConsultDialog()
        initStatusBar()
//        ModularServiceManager.provide(IConsultantService::class.java).showConfideListDialog(this)
//        ActionCountUtils.count("daoyi_advertisement_page|daoyi_advertisement_visit","17")
//        Glide.with(this)
//            .load(R.drawable.confide__free)
//            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
//            .into(confide_Free)
        if (isFromRed) {
            ToastUtil.toastLong(this@ConfideHomeActivity, "红包已领取成功 可立即点击拨打")
        }

        if (!confidedId.isNullOrBlank() && !doctorId.isNullOrBlank()) {
            ConfideWebServiceImpl().connectionJava(
                confidedId.toInt(),
                3,
                this@ConfideHomeActivity,
                null
            ) {
                showDoctorDetail(confidedId, doctorId)
            }
        }
    }

    private fun showDoctorDetail(confideId: String, doctorId: String) {
            val url = HttpConfig.MH5_URL + ConfideRoute.h5ConfideIntro(confideId)+"&payPage=1"
            ConfideBottomSheetDialogFragment()
                .showBottomSheetDialog(this@ConfideHomeActivity, url, doctorId)
    }

    override fun onResume() {
        super.onResume()
        handleFree()
    }

    private fun handleFree() {
        //登录了回来之后就不显示了
        val isLogin = (findRouteService(IUserService::class.java).isLogin())
        findViewById<View>(R.id.confide_Free).visibility = if (isLogin) View.GONE else View.VISIBLE
        if (!isLogin) {
            val controller: DraweeController = Fresco.newDraweeControllerBuilder()
                .setUri(Uri.parse("res://drawable/" + R.drawable.first_order))
                .setOldController(confide_Free.controller)
                .setAutoPlayAnimations(true) // 是否自动播放Gif动画
                .build()
            confide_Free.controller = controller
        }
        if (isLogin) {
            findViewById<View>(R.id.confideRed).visibility =
                if (listenFree) View.VISIBLE else View.GONE
            (quick_consult_btn.layoutParams as? ViewGroup.MarginLayoutParams)?.rightMargin =
                if (listenFree) dp48 / 2 else 0
        }

    }

    /**
     * 初始化状态栏位置
     */
    private fun initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window?.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window?.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window?.statusBarColor = Color.WHITE
            window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
    }

    /**
     * 监听控制一键倾诉浮层的显示与隐藏
     */
    private fun initQuickConsultDialog() {
        rv_list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    quick_consult_card.visibility = View.VISIBLE
                }
//                val layoutManager: RecyclerView.LayoutManager = recyclerView?.layoutManager!!
//                val linearManager = layoutManager as LinearLayoutManager
//                if (linearManager is LinearLayoutManager) {
//                    val firstItemPosition = linearManager.findFirstCompletelyVisibleItemPosition()
//                    if (firstItemPosition > 3) {
//                        quick_consult_card.visibility = View.VISIBLE
//                    }else {
//                        quick_consult_card.visibility = View.GONE
//                    }
//                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dy <= 0) {
                    //向上滚动恢复显示
                    quick_consult_card.visibility = View.VISIBLE
                } else {
                    //向下滚动隐藏
                    quick_consult_card.visibility = View.GONE
                }
            }
        })
    }

    /**
     * 初始化一键倾诉浮层的点击事件
     */
    private fun initClick() {
        quick_consult_card.setOnClickListener {
            ActionCountUtils.record("listen_counselor_list_page", "akey_consult_icon_click")
            if (!PhoneCallIn.loginByOneKeyLogin(this, true)) {
                return@setOnClickListener
            }
            bottomSheetDialogFragment = ConfideBottomSheetDialogFragment()
            bottomSheetDialogFragment?.showBottomSheetDialog(
                this as FragmentActivity,
                HttpConfig.MH5_URL + ConfideRoute.h5ConfideIntro("0"),
                "0",
                true
            )


        }
    }

    private fun initView() {
        img_back.setOnClickListener {
            finish()
        }
        img_mine.setOnClickListener {
            //跳转倾诉列表
            ActionCountUtils.record("listen_counselor_list_page", "topright_corner_icon_click", "1")
            if (!PhoneCallIn.loginByOneKeyLogin(this, true)) {
                return@setOnClickListener
            }
            val h5Paramsqing = H5Params(YDL_H5 + "confideOrderList", null)
            NewH5Activity.start(this, h5Paramsqing)
        }
        findViewById<View>(R.id.img_customer)?.setOnClickListener {
            ActionCountUtils.record("listen_counselor_list_page", "topright_corner_icon_click", "2")
            val imService = findRouteService(IImService::class.java)
            imService.startP2PXiaoYi(this)
        }
        findViewById<View>(R.id.img_help)?.setOnClickListener {
            ActionCountUtils.record("listen_counselor_list_page", "topright_corner_icon_click", "3")
            val params = H5Params("https://activity.yidianling.com/activity/qs", "")//倾诉指南
            params.isShowMenu = true
            NewH5Activity.start(this, params)
        }
        ll_bar_root.setOnClickListener {

        }
        //用于滑动筛选模块置顶
        if (null == listScrollListener) {
            listScrollListener = ConfideHomeRecycleViewListener()
        }
        rv_list.addOnScrollListener(listScrollListener!!)
        //用于显示筛选悬浮按钮
        if (null == listSuspendListener) {
            listSuspendListener = ConfideHomeRecyleSuspendListener()
        }
        rv_list.addOnScrollListener(listSuspendListener!!)
        rv_list.addOnScrollListener(YDLImageRecyclerOnScrollListener(ConfideHomeActivity@ this))
        if (rv_list.itemAnimator is SimpleItemAnimator) {
            (rv_list.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        }
    }

    /**
     * 初始化适配器
     */
    private fun initAdapter() {
        if (null == mConfideAdapter) {
            mConfideAdapter = ConfideHomeAdapter(ConfideHomeActivity@ this, mConfideEvent!!, this)
        }
        rv_list.addItemDecoration(FilterItemDecoration())
        val layoutManager =
            WrapContentLinearLayoutManager(this, WrapContentLinearLayoutManager.VERTICAL, false)
        rv_list.layoutManager = layoutManager
        rv_list.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader)
        rv_list.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader)
        rv_list.setArrowImageView(R.drawable.confide_downgrey)
        rv_list.setLoadingListener(this)
        rv_list.adapter = mConfideAdapter
    }

    /**
     * 倾诉首页数据请求结果
     */
    override fun confideHomeResponse(list: MutableList<ConfideHomeDataBean>) {
        initParam()
        hideError()
        cacheList?.addAll(0, list)
        updateAdapter()
        setSuspendListener()
        v_filterView.refreshView()
    }

    /**
     * 设置筛选模块悬浮顶部监听数据
     */
    private fun setSuspendListener() {
        listSuspendListener?.setFilterView(v_filterView, vFilterLine)
        listSuspendListener?.setSectionAdapter(mConfideAdapter!!)
    }

    private fun setHideFilterView() {
        v_filterView.visibility = View.INVISIBLE
        v_filterView.setHomeView(this)
    }

    /**
     * 更新适配器数据
     */
    private fun updateAdapter() {
        rv_list.removeAllViews()
        //数据重组
        ConfideHomeUtils.resetData(cacheList!!, v_filterView, listScrollListener!!)
        setHideFilterView()
        mConfideAdapter?.updateItems(cacheList!!)
        mConfideAdapter?.notifyDataSetChanged()
        rv_list.refreshComplete()
    }

    /**
     * 更新适配器数据（用于播放 暂停 状态切换 更新整体数据）
     */
    private fun updateAdapterForPlayStatus() {
        mConfideAdapter!!.updateItems(cacheList!!)
        mConfideAdapter!!.notifyDataSetChanged()
    }

    private fun clearCacheData() {
        if (null == cacheList) {
            cacheList = ArrayList()
        } else {
            (cacheList as ArrayList).clear()
        }
    }

    /**
     * 根据筛选条件 更新为你推荐数据
     */
    private fun updateCacheDataByRecommend(bean: ConfideHomeDataBean) {
        //需要重置一下页码
        page = 1
        if (null == cacheList) {
            cacheList = ArrayList()
        }
        if (bean?.body == null) {
            v_filterView.visibility = View.GONE
        } else if (null != bean.body && bean.body.size < 2) {
            v_filterView.visibility = View.GONE
        } else {
            v_filterView.visibility = View.VISIBLE
        }
        var soundBean: ConfideHomeDataBean? = null
        //从后往前循环 这样remove的时候不会有问题
        for (index in (0..(cacheList!!.size - 1)).reversed()) {
            if (cacheList!![index].type == IConfideHomeConfig.TYPE_RECOMMEND) {
                //移除原有的为你推荐数据
                (cacheList as ArrayList).removeAt(index)
            } else if (cacheList!![index].type == IConfideHomeConfig.TYPE_SOUND) {
                //移除听声寻人数据 重新添加
                soundBean = cacheList!![index]
                (cacheList as ArrayList).removeAt(index)
            }
        }
        if (bean?.body != null) {
            bean.recommendId = page
            //添加为你推荐数据
            (cacheList as ArrayList).addAll(ConfideHomeUtils.getRecommendList(bean))
        }
        //添加听声寻人数据
        if (null != soundBean) {
            (cacheList as ArrayList).add(soundBean)
        }
        listScrollListener?.moveToPosition(rv_list)
    }

    /**
     * 为你推荐 翻页 请求结果
     */
    override fun recommendListMoreResponse(bean: ConfideHomeDataBean) {
        dismissProgressDialog()
        rv_list.loadMoreComplete()
        bean.recommendId = page
        if (bean.body?.size ?: 0 == 0) {
            rv_list.loadMoreComplete()
            mConfideAdapter!!.notifyDataSetChanged()
            return
        }
        (cacheList as ArrayList).add(bean)
        val size = mConfideAdapter!!.itemCount
        mConfideAdapter!!.addItems(ConfideHomeUtils.getRecommendList(bean))
        mConfideAdapter!!.notifyItemInserted(if (size > 0) size + 1 else 0)
    }

    /**
     * 为你推荐 筛选 请求结果
     */
    override fun recommendListResponse(bean: ConfideHomeDataBean) {
        dismissProgressDialog()
        rv_list.loadMoreComplete()
        updateCacheDataByRecommend(bean)
        mConfideAdapter!!.updateItems(cacheList!!)
//        if (bean.body == null || bean.body.size < 10) {
//            rv_list.setNoMore(true)
//        } else {
//            rv_list.loadMoreComplete()
//        }
        mConfideAdapter!!.notifyDataSetChanged()
        if (!bean.body.isNullOrEmpty()) {
            listenFree = bean.body[0].listenFree ?: false
            handleFree()
        }
    }

    /**
     * 倾诉首页数据请求失败
     */
    override fun confideHomeRequestFail() {
        showError()
    }

    override fun showProgress() {
    }


    /**
     * 更新section的播放状态
     * 点击列表中的一个播放按钮 其他播放按钮要显示暂停状态
     * @param sectionId
     * @param index 模块中点击播放的索引位置
     */
    override fun updataPlayStatu(type: Int?, index: Int, recommendId: Int, isPlaying: Boolean) {
        ConfideHomeUtils.changeCacheDataPlay(cacheList, type, index, recommendId)
        updateAdapterForPlayStatus()
    }

    override fun moveToFilter() {
        rv_list.scrollBy(0, 400)
        listScrollListener?.moveToPosition(rv_list)
    }

    override fun showSortPopupWindow(
        v_line_top: View,
        tvSort: DrawableRightTextView,
        bodyBean: ConfideHomeBodyBean?
    ) {
        ActionCountUtils.record("listen_counselor_list_page", "choice_filter_click")
        if (null == allFiltersBean) {
            return
        }
        if (v_filterView.visibility == View.GONE || v_filterView.visibility == View.INVISIBLE) {
            listScrollListener?.moveToPosition(rv_list)
        }
        mConfideEvent?.showSortPopupWindow(
            v_line_top,
            v_filterView,
            bodyBean,
            allFiltersBean!!,
            mConfideAdapter!!
        )
    }

    override fun showSexAgePopupWindow(
        v_line_top: View,
        tvSexAge: DrawableRightTextView,
        bodyBean: ConfideHomeBodyBean?
    ) {
        ActionCountUtils.record("listen_counselor_list_page", "choice_filter_click")
        if (null == allFiltersBean) {
            return
        }
        if (v_filterView.visibility == View.GONE || v_filterView.visibility == View.INVISIBLE) {
            listScrollListener?.moveToPosition(rv_list)
        }
        mConfideEvent?.showSexAgePopupWindow(
            v_line_top,
            v_filterView,
            bodyBean,
            allFiltersBean!!,
            mConfideAdapter!!
        )
    }

    override fun showGoodPopupWindow(
        v_line_top: View,
        tvGood: DrawableRightTextView,
        bodyBean: ConfideHomeBodyBean?
    ) {
        ActionCountUtils.record("listen_counselor_list_page", "choice_filter_click")
        if (null == allFiltersBean) {
            return
        }
        if (v_filterView.visibility == View.GONE || v_filterView.visibility == View.INVISIBLE) {
            listScrollListener?.moveToPosition(rv_list)
        }
        mConfideEvent?.showGoodPopupWindow(
            v_line_top,
            v_filterView,
            bodyBean,
            allFiltersBean!!,
            mConfideAdapter!!
        )
    }

    private fun showError() {
        rv_list.refreshComplete()
    }

    private fun hideError() {
        rv_list.refreshComplete()
        rv_list.visibility = View.VISIBLE
    }

    override fun showError1(msg: String?) {
        rv_list.loadMoreComplete()

        msg?.let {
            ToastHelper.show(msg)
        }
    }

    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        super.onDestroy()
        mConfideEvent!!.destoryPlayer()
    }

    override fun onBackPressed() {
        if (isSplash) {
            //跳转主页
            PhoneCallIn.getAppService().mainIntent(this)
        }
        super.onBackPressed()
    }
}