package com.yidianling.home.ui.fragment

import android.app.Dialog
import android.content.Context
import android.text.TextUtils
import android.view.View
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.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.bean.StatusBarOptions
import com.ydl.ydlcommon.data.http.BaseResponse
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.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.common.tools.ToastUtil
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.IHomeContract
import com.yidianling.home.constract.YdlHomeViewHolderConstract
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.im.api.service.IImService
import com.yidianling.user.api.service.IUserService
import kotlinx.android.synthetic.xlzx.home_fragment_home_module.*
import kotlinx.android.synthetic.xlzx.home_layout_home_module_content.*
import kotlinx.android.synthetic.xlzx.home_layout_home_module_input.*
import kotlin.properties.Delegates


/**
 * @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")
class YdlHomeFragment : BaseMvpFragment<IHomeContract.View, HomePresenterImpl>(),
    IHomeContract.View,
    SwipeRefreshLayout.OnRefreshListener {

    private lateinit var mActivity: FragmentActivity
    private lateinit var mContext: Context

    private var adapter: YdlHomeAdapter? = null
    private var homeEvent: HomeImpl? = null
    private var dialog: CouponDialog? = null

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

    /**
     * tablayou上次选中的tab下标
     */
    private var confideLastSelectPosition = 0
    private var confideLastSelectType = ""
    /**
     * 咨询tablayout上次选中的西边
     */
    private var consultLastSelectPosition = 0
    private var consultLastSelectType= ""
    /**
     * 悬浮tablayout监听事件
     */
    private var scrollListner: HomeConfideRecyleSuspendListener? = null

    /**
     * 如果是第一次加载，则调用所有接口进行刷新，否则，只调用咨询和倾诉接口
     */
    private var isFromCreate: Boolean = true
    var startTime by Delegates.notNull<Long>()
    var endTime by Delegates.notNull<Long>()
    override fun layoutResId(): Int {
        return R.layout.home_fragment_home_module
    }

    override fun getStatusViewOptions(): StatusBarOptions {
        return StatusBarOptions(isAddStatusView = true, statusBarDarkMode = true)
    }

    override fun initDataAndEvent() {
        mActivity = requireActivity()
        mContext = requireContext()
        homeEvent = HomeImpl(mActivity!!, this)
        initView()
        initAdapter()
    }

    private fun initAdapter() {
        mPresenter?.localHomeData(mContext, "home_data_xlzx.json")
        adapter = YdlHomeAdapter(mContext, homeEvent!!, ArrayList())
        val layoutManager =
            LinearLayoutManager(context)
        home_module_fragment_recycler.layoutManager = layoutManager
        home_module_fragment_recycler.adapter = adapter

        scrollListner = HomeConfideRecyleSuspendListener()
        home_module_fragment_recycler.addOnScrollListener(scrollListner!!)
    }

    private fun initView() {


        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_swipe_refresh_layout.isEnabled = true
        etSearch.setOnClickListener { homeEvent?.searchTvClick("") }

        home_page_xiaoyi.setOnClickListener {
            activity?.let {
                ModularServiceManager.provide(IImService::class.java).startP2PXiaoYi(mActivity!!)
            }
        }



    }

    /**
     * 初始化状态栏位置
     */
//    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_search_toolbar_bg.layoutParams as RelativeLayout.LayoutParams
//            lp1.height = (homeTitleBarHeight + statusBarHeight).toInt()
//            view_search_toolbar_bg.layoutParams = lp1
//
//            val lp2 = toolbar.layoutParams as CollapsingToolbarLayout.LayoutParams
//            lp2.topMargin = statusBarHeight
//            toolbar.layoutParams = lp2
//        }
//    }

    override fun initDataAndEventLazy() {
    }

    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
    }

    /**
     * 获取倾述列表数据
     * @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
                img_ad_card.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)
                    }
                    //定制咨询点击事件埋点
                    ActionCountUtils.count(HomeBIConstants.YDL_HOME_SEARCH_TAG,"1")

                }
            } else {
                img_ad.visibility = View.GONE
                img_ad_card.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(mActivity!!, act.imageBanner, act.linkUrl, act.title)
                    aa?.show()
                    aa?.setOnDismissListener {
                        if (!TextUtils.isEmpty(act.title)) {
                            img_ad.post {
                                val heig = StatusBarUtils.getStatusBarHeight(mContext!!)
                                var location = IntArray(2)
                                img_ad.getLocationInWindow(location)
                                ActivityGuideDialog(
                                    mActivity!!,
                                    act.imageUrl,
                                    act.title,
                                    location[1] - heig,
                                    location[0]
                                ).show()
                                //99元3小时弹出事件
                                ActionCountUtils.count(HomeBIConstants.YDL_HOME_POPUPWINDOWS_PAGE_POPUP,"1")
                            }
                        }
                    }
                }
                //仅展示一次，以后不再展示
                SharedPreferencesEditor.putString(act.imageBanner, "yes")
            }
        }
    }

    override fun homeDataResponse(list: MutableList<HomePagerDataBean>) {
        home_swipe_refresh_layout.isRefreshing = false
        //更新首页数据
        if (list.size > 0) {
            list[0].type = YdlHomeViewHolderConstract.HOME_IMAGE_BANNER
        }
        adapter?.updateItems(list)
        //每次全局更新后重置下标位
        confideLastSelectPosition = 0
        consultLastSelectPosition = 0

        for (bean in list) {
            //咨询模块
            if (bean.type == YdlHomeViewHolderConstract.BUTTON_BANNER_VIEW) {
                consultLastSelectType = bean.headerBean!!.consultCategoryData!![0].id.toString()
            }
        }
    }

    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) {
        if (home_swipe_refresh_layout != null) {
            home_swipe_refresh_layout.isRefreshing = false
        }
        if (!TextUtils.isEmpty(msg)){
            ToastHelper.show(msg)
        }
    }

    override fun couponDataResponse(data: List<CouponBean>) {
        showCouponDialog(data)
    }

    private fun showCouponDialog(data: List<CouponBean>) {
        if (dialog == null) {
            dialog = CouponDialog(activity, data, homeEvent?.clickEnsure(data))
        }

        if (!dialog!!.isShowing) {
            dialog?.show()
        }

    }

    override fun receiveCoupon(data: List<CouponBean>) {
        mPresenter?.receiveCoupon(data)
    }

    override fun receiveCouponResponse(data: BaseResponse<Any>) {
        if (data.code == 200) {
            dialog?.updateStatus(CouponDialog.STATUS_GET)
        } else {
            ToastHelper.show(data.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(mActivity!!)
    }

    private fun hideConsultAssistantDialog() {
        ModularServiceManager.provide(IConsultantService::class.java).hideConsultAssistantDialog()
    }
    override fun onStop() {
        super.onStop()
        endTime=System.currentTimeMillis()
        ActionCountUtils.count(HomeBIConstants.YDL_HOME_DWELL_TIME,(endTime-startTime).toString())
    }
    override fun onResume() {
        super.onResume()
        startTime=System.currentTimeMillis()
        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)

            }
            mPresenter?.prepareCoupon(mActivity!!)

            //走咨询助理浮层展示逻辑，是否展示由内部条件与接口判断
            showConsultAssistantDialog()
        }
    }
}